A while loop repeats its body for as long as its condition is true. Java checks the condition before every pass, so the body can run zero times, and something in the body must eventually make the condition false or the loop never ends. Trace one with a table of each variable after every pass.
Quick check
After int n = 6; n = n / 4; what is the value of n?Show answerHide answer
It is 1. Both operands are
int, so the division drops the remainder: 6 / 4 is 1.With int k = 3, is k <= 3 true or false?Show answerHide answer
It is
true, because<=includes the case where the values are equal.A while loop's condition is false the first time it is checked. How many times does the body run?Show answerHide answer
Zero times. The condition is tested before the body, so the whole loop is skipped.
Know these already? Jump to the practice questions
What you'll be able to do
- Identify the condition, the body and the update of a
whileloop. - Determine a loop's output, final values and number of passes with a trace table.
- Explain why a loop runs zero times or never stops.
- Use a sentinel value or a flag to decide when a loop stops.
Key terms
Iteration
One complete pass through the body of a loop.
- In plain English
- One lap of the loop.
- Don't write
- "Iterations equal condition checks."
Infinite loop
A loop whose condition never becomes false.
- In plain English
- A loop with no way out.
- Don't write
- "An infinite loop eventually stops."
Sentinel value
A special value after the real data that marks its end; the loop stops there without processing it.
- In plain English
- A stop sign at the end of the data.
- Don't write
- "The sentinel is counted as data."
Flag
A boolean variable that records whether something has happened; the loop's condition tests it.
- In plain English
- A switch the body flips to say "done".
- Don't write
- "A flag is the loop's counter."
How does a while loop run?
A while loop has a condition in parentheses and a body in braces. Java repeats these steps:
- Evaluate the condition.
- If
true, run the whole body, then go back to step 1. - If
false, skip to the statement after the loop.
Most loops also need a variable set before the loop and an update in the body that can make the condition false.
int n = 1;
while (n < 20)
{
System.out.print(n + " ");
n = n * 3;
}
System.out.println("end " + n);
n starts at 1, so the first pass prints 1 and the update makes n 3. The next passes print 3 and 9. At 27, 27 < 20 is false, so the loop ends, and the output is the single line 1 3 9 end 27.
The while syntax is not on the Java Quick Reference: Learn this.
Check yourself
Show answerHide answer
4 times: it is true for 1, 3 and 9 and false for 27. When a loop ends because its condition is false, the condition is checked once more than the body runs.
How do you trace a while loop?
Make a trace table with one column per variable and one row per pass, starting from the initial values.
int num = 472;
int sum = 0;
while (num > 0)
{
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);
| Pass | num > 0? | sum | num |
|---|---|---|---|
| start | 0 | 472 | |
| 1 | true | 2 | 47 |
| 2 | true | 9 | 4 |
| 3 | true | 13 | 0 |
false: stop |
num % 10 is the last digit and num / 10 removes it, so the loop adds the digits and prints 13 after 3 passes, one per digit.
Key idea
Test the condition at the top of every row, and stop the table at the first false.
Check yourself
Show answerHide answer
One pass: sum becomes 9 and num becomes 0, so it prints 9.
When does a loop run zero times or never stop?
A loop runs zero times when its condition is false at the start, such as while (k < 5) with k at 10.
A loop never stops when no pass can make the condition false, usually for one of two reasons:
- The update is missing, so nothing in the condition changes.
- The update jumps past a
!=target. In this loopktakes the values 0, 2, 4, 6, 8 and so on, and is always even, so it never equals 7:
int k = 0;
while (k != 7)
{
k = k + 2;
}
With k < 7 instead, the loop stops once k passes 7.
Check yourself
Show answerHide answer
kgoes 0, 2, 4, 6, 8, and8 < 7isfalse, so the loop stops.
How do sentinels and flags stop a loop?
A sentinel loop processes data until it meets the marker. Here "#" is the sentinel, and the loop counts the characters before it:
String data = "ab3c#xy";
int i = 0;
int count = 0;
while (!data.substring(i, i + 1).equals("#"))
{
count++;
i++;
}
The characters at indexes 0 to 3 are not "#", so count ends at 4; the "#" at index 4 stops the loop and is not counted.
A flag loop stops when the body sets a boolean to record that the job is done:
int k = 1;
boolean found = false;
while (!found && k <= 10)
{
if (k * k > 40)
{
found = true;
}
else
{
k++;
}
}
k rises until 7 * 7, which is 49, is the first square above 40. Then found becomes true and !found ends the loop, leaving k at 7. The k <= 10 part stops the search even if no value is found.
Check yourself
Show answerHide answer
- The first character is the sentinel, so the condition is
falsestraight away and the body never runs.
Worked example 1: Count the passes
Question: How many times does the body of this loop run?
int n = 100;
int steps = 0;
while (n > 1)
{
n = n / 2;
steps++;
}
What tells you the method
"How many times", so trace with a table and count the rows.
Step 1: Trace
n.Pass nafter the passstepsstart 100 0 1 50 1 2 25 2 3 12 3 4 6 4 5 3 5 6 1 6 Why25 / 2is 12 and3 / 2is 1, becauseintdivision drops the remainder.Step 2: Stop at the first
false.After pass 6,
1 > 1isfalse, so the loop ends.WhyThe condition is tested before every pass, including the one that would be pass 7.
Check it
Starting at 200 gives 7 passes: one pass reaches 100, then this trace repeats. Doubling the start adds one pass, so the count grows like log₂ n.
Answer
6
Worked example 2: Design a loop that searches upward
Question: Design a code segment that prints the smallest power of 2 that is at least int limit, then state what it prints when limit is 100.
What tells you the method
The number of doublings isn't known in advance, so use a while loop.
Step 1: State the input, the output and the plan.
Input:
limit. Output: one power of 2. Start a variablepat 1, and double it while it is still belowlimit.WhyThe first value of
pthat is not belowlimitis the answer.Step 2: Write the segment.
int limit = 100; int p = 1; while (p < limit) { p = p * 2; } System.out.println(p);WhyThe condition says when to keep going, the opposite of the stopping rule.
Step 3: Trace it.
ptakes the values 1, 2, 4, 8, 16, 32, 64 and 128. At 128,128 < 100isfalse, so the loop stops and prints 128.Why64 is still below 100, so the loop needs one more doubling.
Check it
With limit 64, the loop stops at 64, because 64 < 64 is false. With limit 1, the body runs zero times and the segment prints 1, which is 2⁰.
Answer
128
Worked example 3: Fix a loop that never stops
Question: This code segment should print 25, the sum of the odd numbers from 1 to 9, but it never stops. Which change makes it print 25?
int k = 1;
int sum = 0;
while (k != 10)
{
sum = sum + k;
k = k + 2;
}
System.out.println(sum);
- A) Condition
k < 10 - B) Condition
k < 9 - C) Update
k = k + 1; - D) First line
int k = 0;
What tells you the method
A loop that never stops, so find why the condition stays true, then trace each fix.
Step 1: Find the cause.
kgoes 1, 3, 5, 7, 9, 11 and is always odd, sok != 10is neverfalse.WhyAdding 2 to an odd number gives an odd number, and 10 is even.
Step 2: Trace each option.
A adds 1, 3, 5, 7 and 9, then stops at 11: 25. B stops before adding 9: 16. C adds 1 to 9: 45. D adds 0, 2, 4, 6 and 8: 20.
WhyB is off by one at the bound, C has the wrong step and D the wrong start.
Check it
In A, the check after k becomes 9 is true, so 9 is added; the next check, 11 < 10, is false.
Answer
A
Your turn
Question: What is printed when this code segment runs?
int n = 50;
boolean done = false;
while (!done)
{
n++;
if (n % 7 == 0)
{
done = true;
}
}
System.out.println(n);
Step 1: Trace the first pass.
!doneistrue, so the body runs:nbecomes 51, and51 % 7is 2, sodonestaysfalse.Step 2: Your go: keep tracing until
donebecomestrue, then give the output.
Show the full solutionHide the solution
Step 2. n becomes 52, 53, 54 and 55, with remainders 3, 4, 5 and 6. At 56, 56 % 7 is 0, so done becomes true, !done is false, and the loop ends after 6 passes.
Answer: 56
Traps
Trap
The body of a while loop always runs at least once.
It seems right because the body is written inside the loop. But the condition is tested before the first pass, so a condition that starts false skips the body entirely.
What is t after int t = 10; while (t < 5) { t++; } runs?
10 < 5isfalse, so the body never runs.
Trap
The loop stops the moment its condition becomes false, even in the middle of the body.
It seems right because the condition describes when the loop should stop. But Java checks the condition only at the top of each pass, so the rest of the body still runs.
What is printed by int a = 0; while (a < 3) { a = a + 5; System.out.print(a); }
5. After a becomes 5 the condition is false, but the print in the same pass still runs; the loop ends at the next check.
Trap
A loop with a != condition stops as long as the variable keeps changing.
It seems right because the variable moves toward the target. But if the update can jump over the target, the condition never becomes false; < or > is safer.
Does int k = 0; while (k != 9) { k = k + 2; } stop?
No. k is always even, so it never equals 9.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), multiple-choice questions ask what a while loop prints, what a variable holds afterward, how many times the body runs, or which change fixes a loop. In free response, you write while loops in your own methods when the number of passes depends on the data.
Practice questions
- Recall A
whileloop ends when its condition isfalse, after 5 checks of the condition in total. How many times did the body run?
Show answer
Answer: 4
Marking points:
- The body runs once for each check that is
true. - The last check is the
falseone that ends the loop, so 5 − 1 = 4.
- Apply What is printed when this code segment runs?
int x = 3;
while (x < 40)
{
x = x * 2 + 1;
}
System.out.println(x);
Show answer
Answer: 63
Marking points:
xtakes the values 3, 7, 15, 31 and 63.31 < 40istrue, so one more pass makesx63, and63 < 40isfalse.
- Apply How many times does the body of this loop run?
int n = 0;
int count = 0;
while (n < 25)
{
n = n + 4;
count++;
}
- A) 6
- B) 7
- C) 8
- D) 28
Show answer
Answer: B. n becomes 4, 8, 12, 16, 20, 24 and 28. 24 < 25 is still true, so the seventh pass runs, and 28 < 25 is false.
Why the others are wrong:
- A is
25 / 4withintdivision, which ignores the pass that takesnfrom 24 to 28. - C counts the condition checks, which is one more than the passes.
- D is the final value of
n, not the number of passes.
- Apply What is printed when this code segment runs?
int a = 47;
int b = 12;
int q = 0;
while (a >= b)
{
a = a - b;
q++;
}
System.out.println(q + " " + a);
Show answer
Answer: 3 11
Marking points:
agoes 47, 35, 23, 11, andqcounts the 3 subtractions.11 >= 12isfalse, so the loop stops withaat 11.
- Exam-style Which loop never stops?
- A)
int k = 1; while (k < 100) { k = k * 2; } - B)
int k = 100; while (k > 0) { k = k / 2; } - C)
int k = 1; while (k != 50) { k = k + 2; } - D)
int k = 0; while (k < 10) { k = k + 3; }
Show answer
Answer: C. k starts odd and goes up by 2, so it is always odd and never equals 50.
Why the others are wrong:
- A jumps from 64 to 128, past 100, but
<stops it anyway. - B reaches 0, because
intdivision takes 1 / 2 to 0. - D jumps from 9 to 12 without ever equaling 10, but
<stops it at 12.
- Exam-style The code segment should print how many digits of
numare greater than 4, which is 2 for 3528, but it never stops. Give the number of the line that causes this.
1: int num = 3528;
2: int big = 0;
3: while (num > 0)
4: {
5: if (num % 10 > 4)
6: {
7: big++;
8: }
9: num = num % 10;
10: }
11: System.out.println(big);
Show answer
Answer: Line 9.
Marking points:
num % 10keeps only the last digit, sonumbecomes 8 and stays 8, and8 > 0istrueforever.- Line 9 should be
num = num / 10;, which removes the last digit; then the code prints 2.
- Recall What is the name for a special value placed after the data to mark where a loop should stop?
Show answer
Answer: Sentinel value
Marking points:
- The loop stops when it reaches the sentinel value and does not process it as data.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- The condition is tested before each pass; a
falsestart means zero passes. - The body needs an update that can make the condition
false. - When the condition ends the loop, it is checked once more than the body runs.
- A trace table has a row per pass; stop it at the first
falsetest. - An update can jump past a
!=target, so prefer<or>when the step is larger than 1. - A sentinel marks the end of the data; a flag records that the job is done.