AP Computer Science A · Unit 2 lecture · Part 6 of 12 · 9 min

2.7 while loopsRepeat while it's true

Mr. Thompkins
Loops are where computers earn their keep: they repeat work a million times without getting bored. The price is that you have to be precise about when a loop stops. Let's learn to trace one pass at a time.

A while loop repeats its body as long as its condition is true. Java checks the condition before every pass, including the very first one. If it's true, the body runs and Java goes back to check again. If it's false, the loop ends and the program continues after the closing brace. If the condition is false from the start, the body runs zero times.

n > 0 ?truebody: use n % 10, then n /= 10check againfalsefirst line after the loopfalse at the start: 0 passes
A while loop: test, body, test, body, and so on. The test comes first every time.

Something in the body must eventually make the condition false. If nothing does, you get an infinite loop: it never stops. while (n > 0) { sum += n; } with no change to n runs forever. The other classic mistake is an off-by-one error, where the loop runs one pass too many or one too few, usually because of < versus <=.

A return statement inside a loop ends the whole method at once, loop and all. That's useful when you're searching for something: as soon as you find it, return.

?Wait, how did n % 10 and n / 10 work on digits?
For a positive int n, n % 10 is its last digit (5308 % 10 is 8), and n / 10 drops the last digit (5308 / 10 is 530, because integer division throws away the decimal). Repeat both and you walk through the digits from right to left.
1int n = 5308;2int sum = 0;3int passes = 0;4while (n > 0)15{6    sum += n % 10;27    n /= 10;38    passes++;9}10System.out.println(sum + " " + passes);
  1. line 4 Checked before every pass, including the first
  2. line 6 n % 10 is the last digit
  3. line 7 Drops the last digit: this moves n toward 0
output › 16 4
Adding up the digits of 5308, run under Java 17.
Passn % 10sumn aftern > 0 next?
start05308true
188530true
20853true
33115true
45160false: stop
The trace table for that loop: one row per pass. The last column is the check that happens before the next pass.

while loops shine when you don't know in advance how many passes you'll need. How many years until a savings account doubles at 7 percent a year? Start with double money = 1000.0; int years = 0; and loop while (money < 2000) { money *= 1.07; years++; }. It stops after 11 years, when money first reaches 2000 or more (about 2104.85).

?Wait, what does money *= 1.07 do?
It's compound assignment from Unit 1: money = money * 1.07. Multiplying by 1.07 adds 7 percent. After one year 1000.0 becomes 1070.0, after two years 1144.9, and so on.
Pause and think
int k = 10; while (k < 5) { k++; } System.out.println(k); What is printed, and how many times does the body run?
I thought about it. Show me
10 is printed, and the body runs zero times. The condition 10 < 5 is false on the very first check, so Java skips the loop entirely.
Trace a while loop

What is printed?

int n = 6;
int steps = 0;
while (n != 1)
{
    if (n % 2 == 0)
    {
        n /= 2;
    }
    else
    {
        n = 3 * n + 1;
    }
    steps++;
}
System.out.println(steps);
  1. Set up a trace table with columns for n and steps. Start: n is 6, steps is 0. 6 != 1, so enter the loop.
    Why?
    Check the condition before every pass, including the first.
  2. Pass 1: 6 is even, so n becomes 3. steps is 1. Pass 2: 3 is odd, so n becomes 10. steps is 2.
  3. Pass 3: 10 becomes 5 (steps 3). Pass 4: 5 is odd, so 16 (steps 4). Pass 5: 8 (steps 5). Pass 6: 4 (steps 6). Pass 7: 2 (steps 7). Pass 8: 1 (steps 8).
  4. Check again: n is 1, so 1 != 1 is false. The loop ends, and 8 is printed.
    Why?
    Don't stop the trace one pass early. The last pass is the one that makes the condition false.

Answer: 8 (n goes 6, 3, 10, 5, 16, 8, 4, 2, 1)

Stuck? Get a hint
  1. Make a table with n and steps. Write a new row after every pass.
  2. Even: halve it. Odd: triple it and add 1. Then add 1 to steps.
  3. Stop only when the check finds n equal to 1.
Check yourself
Which loop never ends?
  1. Aint a = 1; while (a < 100) { a *= 2; }
  2. Bint b = 10; while (b > 0) { b -= 3; }
  3. Cint c = 0; while (c != 7) { c += 2; }
  4. Dint d = 50; while (d > 1) { d /= 2; }
Show the answer

C. c goes 0, 2, 4, 6, 8, 10, and so on. It jumps right over 7, so c != 7 is always true and the loop never stops. The others all move toward making their conditions false: a doubles past 100, b drops below 1, and d halves down to 1. Choice B is the usual suspect, but b reaches -2 and stops.

  • A while loop checks its condition before every pass. False at the start means zero passes.
  • The body must move the loop toward stopping, or it's an infinite loop.
  • Trace with a table: one row per pass, and check the condition after every update.
  • return inside a loop ends the method immediately.