2.7 - while Loops
Iteration is repetition. An iteration statement repeats a block of code zero or more times, for as long as its controlling boolean expression stays
true.You need iteration whenever a step has to happen more than once, especially when you don’t know ahead of time how many times. “Keep adding $15 to your savings until you have $100” is a loop: the same step repeats until a condition is met.
An infinite loop happens when that boolean expression never becomes false, so the loop just never stops.
If the boolean expression is
false right from the start, the loop body never runs, not even once.int n = 10; while (n < 5) { System.out.println(n); // never runs, since 10 < 5 is false the first time }
An off by one error is when your loop runs one time too many, or one time too few, usually from a small mistake in the condition.
// goal: print 1 through 5 int i = 1; while (i < 5) { // off by one: stops after 4 System.out.println(i); i++; } // prints 1, 2, 3, 4 (fix it with i <= 5)
A while loop checks its condition before every single iteration, including the very first one. As long as it’s
true, the loop body runs. Once it’s false, the loop stops.int count = 0; while (count < 5) { System.out.println(count); count++; } // prints 0, 1, 2, 3, 4
Here’s a loop where you don’t know the number of repetitions in advance:
int savings = 0; int weeks = 0; while (savings < 100) { savings += 15; weeks++; } System.out.println(weeks + " weeks, $" + savings); // prints 7 weeks, $105
Tracing it with a table makes the exam questions easier. Check the condition, run the body if it’s true, repeat:
Check | Condition | savings after body | weeks after body |
1 | 0 < 100 is true | 15 | 1 |
2 | 15 < 100 is true | 30 | 2 |
3 | 30 < 100 is true | 45 | 3 |
4 | 45 < 100 is true | 60 | 4 |
5 | 60 < 100 is true | 75 | 5 |
6 | 75 < 100 is true | 90 | 6 |
7 | 90 < 100 is true | 105 | 7 |
8 | 105 < 100 is false | 105 (loop ends) | 7 (loop ends) |
// infinite loop example, be careful of this int count = 0; while (count < 5) { System.out.println(count); // forgot count++, so count stays 0 and count < 5 is always true }
To avoid an infinite loop, make sure something in the loop body moves the condition toward false, like
count++ does in the first example.