Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops A loop is: Java provides three forms for explicit loops:

Similar presentations


Presentation on theme: "Loops A loop is: Java provides three forms for explicit loops:"— Presentation transcript:

1 Loops A loop is: Java provides three forms for explicit loops:
a block of code that executes repeatedly while some condition holds true. Java provides three forms for explicit loops: while for do..while The conditions in loops are written as in if statements See examples on next slides Fundamentals of Software Development 1

2 Loops while loop while (condition) { statement; … statement; }
for (start; condition; step) { statement; … statement; } for loop do { statement; … statement; } while (condition); do-while loop Fundamentals of Software Development 1

3 for-loop example Problem: Display the square of all numbers from 1 to 99 Solution idea: Use a counting variable What should the variable start at? The loop should continue while …? Each time through the loop, increment the variable by …? for (int k = 1; k < 100; ++k) { System.out.println(k*k); } Alternative solution: for (int k = 1; k <= 99; ++k) { System.out.println(k*k); } Both solutions are correct; the first risks round-off error in its stopping condition Fundamentals of Software Development 1

4 while-loop example Problem: Input numbers from the console, displaying the square of each, stopping when the user inputs a negative number Solution: First do an input, then use a while loop that runs while inputs are nonnegative Fundamentals of Software Development 1

5 Problem: Input numbers from the console, displaying the square of each, stopping when the user inputs a negative number Scanner inputStream = new Scanner(System.in); double input; input = inputStream.nextDouble(); while (input >= 0) { System.out.println(input*input); } Fundamentals of Software Development 1

6 for loops versus while loops
for (int i = 0; i < 7; i = i + 1) { System.out.println (i + " " + i*i); } int i = 0; while (i < 7) { System.out.println (i + " " + i*i); i = i + 1; } The two boxes are equivalent. Typically we use: for when we know in advance how many times the loop will execute while when something that happens in the loop determines when the loop exits do..while when we want a while loop that always does at least one iteration Fundamentals of Software Development 1


Download ppt "Loops A loop is: Java provides three forms for explicit loops:"

Similar presentations


Ads by Google