Unit 2 · 20 min
2.7 while Loops
A while loop repeats its body for as long as its condition stays true, and checks the condition before every pass.
Summary, objectives and course and exam description (CED) codes
Iteration is a form of repetition: an iteration statement repeats a segment of code zero or more times as long as its Boolean expression is true. In a while loop the Boolean expression is evaluated before every iteration, including the first, so the body never runs if it starts false. A loop whose expression is always true is an infinite loop, and a loop that runs one time too many or too few has an off by one error.
By the end of this session you can
- 2.7.A Identify when an iterative process is required to achieve a desired result.
- 2.7.B Develop code to represent iterative processes using while loops and determine the result of these processes.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. When you need iteration
Iteration is one kind of repetition. An iteration statement changes the flow of control: it sends the program back to run the same segment of code again, for as long as the Boolean expression that controls the loop stays true. That can mean many times, once, or zero times 2.7.A.1. You need iteration when a task repeats the same steps many times, or when you do not know how many times the steps must repeat until the program is running: “add interest until the savings reach 1000”, “keep halving until the value is 1”.
Without a loop you would copy the same lines again and again, and you could not handle a number of repetitions that changes.
2. How a while loop runs
A while loop is a type of iterative statement. The Boolean expression is evaluated before each iteration of the loop body, including the first. When it is true, the body runs. This continues until the expression is false, and then the iteration ends 2.7.B.1.
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--;
}
System.out.println("Liftoff!");
Output:
3
2
1
Liftoff!
| Check | countdown | countdown > 0 | Printed |
|---|---|---|---|
| 1 | 3 | true | 3 |
| 2 | 2 | true | 2 |
| 3 | 1 | true | 1 |
| 4 | 0 | false | (loop ends) |
The Boolean expression was evaluated 4 times; the body ran 3 times. The variable that controls the loop (countdown) is called the loop control variable. A working loop has three parts: it is initialized before the loop, tested in the condition and updated in the body.
Watch out: the condition is only checked at the top. In the example below, steps passes 10 in the middle of the body, but the rest of the body still runs.
int steps = 8;
while (steps < 10) {
steps += 3;
System.out.println("steps = " + steps);
}
Output:
steps = 11
3. Zero iterations
If the Boolean expression is false the first time it is evaluated, the loop body does not run at all 2.7.A.3.
int lives = 0;
while (lives > 0) {
System.out.println("Playing...");
lives--;
}
System.out.println("Game over");
Output:
Game over
This matters when a loop depends on its starting values (initial conditions). Ask: “What must be true before the loop starts for it to work as intended?”
4. Infinite loops
If the Boolean expression of a loop is true every time it is checked, the loop never stops: this is an infinite loop 2.7.A.2. The code compiles, but the program never moves past the loop. Three common causes:
Forgetting the update:
int count = 1;
while (count <= 5) {
System.out.println(count);
}
Updating in the wrong direction:
int count = 1;
while (count <= 5) {
System.out.println(count);
count--;
}
count moves away from 5 (1, 0, -1, -2…), so count <= 5 stays true. (Strictly, count would overflow after about two billion iterations, but for the AP® exam this loop is an infinite loop.)
Skipping over the stopping value with !=:
int n = 0;
while (n != 10) {
n += 4;
}
n goes 0, 4, 8, 12, 16… and is never exactly 10. Writing n < 10 would stop the loop.
A stray semicolon also causes trouble: while (count <= 5); is a loop with an empty body, so count never changes.
5. Off by one errors
An off by one error happens when the loop runs one time too many or one time too few 2.7.A.4. Goal: print the lap numbers 1 to 5.
int lap = 1;
while (lap < 5) {
System.out.print(lap + " ");
lap++;
}
Output:
1 2 3 4
One time too few: when lap is 5, lap < 5 is false. The fix is lap <= 5:
int lap = 1;
while (lap <= 5) {
System.out.print(lap + " ");
lap++;
}
Output:
1 2 3 4 5
Starting at 0 with lap <= 5 would be one time too many (6 iterations). To check any loop, trace the first iteration and the last iteration.
6. Repeat until a goal is reached
while loops are a natural fit when you do not know the number of iterations in advance. A savings account earns 10 percent each year (integer dollars, rounded down). How many years until 100 dollars grows to at least 150?
int balance = 100;
int years = 0;
while (balance < 150) {
balance = balance + balance / 10;
years++;
}
System.out.println(years + " years, balance " + balance);
Output:
5 years, balance 160
| years at check | balance | balance < 150 |
|---|---|---|
| 0 | 100 | true |
| 1 | 110 | true |
| 2 | 121 | true |
| 3 | 133 | true |
| 4 | 146 | true |
| 5 | 160 | false |
Notice balance / 10 is integer division: 121 / 10 is 12 and 133 / 10 is 13.
You can also end a loop early with a condition in the body. Here a boolean variable stops the search at the first multiple of 7 above 50:
int n = 51;
boolean found = false;
while (!found) {
if (n % 7 == 0) {
found = true;
} else {
n++;
}
}
System.out.println("First multiple of 7 above 50: " + n);
Output:
First multiple of 7 above 50: 56
Watch out: if the n++ came before the if, the search would skip testing 51. The order of statements in the body decides whether an early exit happens too early, too late or not at all.
Lock it in: memory hooks
- while loopCheck, run, check, run... stop at the first false check.
- Infinite loopNo progress, no exit: something in the body must move the loop toward false.
- Off by one< or <=? Test the first and the last value before you trust the loop.
Common misconceptions
"A while loop always runs at least once."
Not quite. The Boolean expression is checked before the first iteration. If it is false at the start, the body runs zero times.
"The loop stops the moment the condition becomes false, even in the middle of the body."
Not quite. The condition is only checked at the top, before each iteration. Once the body starts, every statement in it runs before the next check.
"An infinite loop is a compile error."
Not quite. It compiles. It is a logic error: the program keeps running because the Boolean expression never becomes false.
Exam traps
- A semicolon after while (...) makes an empty body: the loop either does nothing or never ends.
- Forgetting the update (count++) inside the body gives an infinite loop.
- while (n != 10) with n += 4 starting at 0 skips over 10 and never stops. Prefer < or > in loop conditions.
- Counting how many times a body runs: starting at 1 with <= n gives n times; starting at 0 with <= n gives n + 1 times.
2PracticeRecall it, then check yourself
In 30 seconds
- Iteration repeats a segment of code zero or more times while the Boolean expression is true.
- A while loop checks its Boolean expression before every iteration, including the first.
- If the expression is false at the start, the body never runs.
- If the expression is always true, the loop is infinite.
- An off by one error runs the loop one time too many or one time too few. Check < versus <= and the starting value.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: while Loops
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- How many times a while loop body can run three cases CED 2.7.A.1, 2.7.A.2, 2.7.A.3
- zero timesthe Boolean expression is false at the start
- some number of timesit becomes false after some iterations
- forever (infinite loop)it always evaluates to true
- Kinds of off by one error two kinds CED 2.7.A.4
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
while looptap to flip
An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.
Example and CED codes -
Repetitiontap to flip
An algorithm building block in which a process repeats itself until a desired outcome is reached. In Java, iteration is a form of repetition.
Example and CED codes -
Infinite looptap to flip
A loop whose Boolean expression always evaluates to true, so it never stops. It compiles; it is a logic error.
Example and CED codes -
Off by one errortap to flip
An error in which a loop runs one time too many or one time too few, often from < versus <= or a wrong starting value.
Example and CED codes -
Loop control variabletap to flip
The variable that controls how many times a loop runs. In a for loop it is the variable set up by the initialization in the header.
Example and CED codes -
Boolean expressiontap to flip
An expression that evaluates to a Boolean value, true or false, such as a comparison with a relational operator or a combination with logical operators.
Example and CED codes
Questions students ask
How does a while loop work in Java?
Java evaluates the Boolean expression. If it is true, the body runs and Java goes back to evaluate the expression again. When the expression is false, the loop ends and the program continues after the loop.
Can a while loop run zero times?
Yes. The expression is checked before the first iteration, so if it is false at the start, the body never runs.
What causes an infinite loop?
A Boolean expression that always evaluates to true, usually because the body never changes the variable in the condition, changes it in the wrong direction, or skips past the stopping value.
What is an off by one error?
A loop that runs one time too many or one time too few, often caused by using < instead of <= (or the reverse) or by starting the loop control variable at the wrong value.
When should I use a while loop instead of a for loop?
Use a while loop when you do not know in advance how many iterations you need, such as repeating until a total reaches a goal. Both kinds can do the same work.