Loops A loop is a block of code
Loops • A loop is: – 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 1
Loops while loop for loop do-while loop Fundamentals of Software Development 1 while (condition) { statement; … statement; } for (start; condition; step) { statement; … statement; } do { statement; … statement; } while (condition); 2
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); } Fundamentals of Software Development 1 Both solutions are correct; the first risks round-off error in its stopping condition 3
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 4
• Problem: Input numbers from the console, displaying the square of each, stopping when the user inputs a negative number Scanner input. Stream = new Scanner(System. in); double input; input = input. Stream. next. Double(); while (input >= 0) { System. out. println(input*input); input = input. Stream. next. Double(); } Fundamentals of Software Development 1 5
for loops versus while loops for (int i = 0; i < 7; i = i + 1) { System. out. println (i + " " + i*i); } The two boxes are equivalent. int i = 0; while (i < 7) { System. out. println (i + " i = i + 1; } " + i*i); • 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 6
- Slides: 6