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.

2.7.A2.7.A.12.7.A.22.7.A.32.7.A.42.7.B2.7.B.1

Reviewed against the CED on

Know this already? Jump to the checkpoint.

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

  1. Iteration repeats a segment of code zero or more times while the Boolean expression is true.
  2. A while loop checks its Boolean expression before every iteration, including the first.
  3. If the expression is false at the start, the body never runs.
  4. If the expression is always true, the loop is infinite.
  5. 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.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 2.7.B.1
    int n = 1;
    int sum = 0;
    while (sum < 20) {
        sum += n;
        n += 2;
    }
    System.out.println(n + " " + sum);
    Show answer

    Answer: D. The sum grows 1, 4, 9, 16, 25 while n grows 3, 5, 7, 9, 11. After sum reaches 16, 16 < 20 is still true, so one more iteration makes sum 25 and n 11; then 25 < 20 is false. "9 16" stops one iteration early, and "9 25" forgets that n is also updated in the last iteration.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 2.7.A.3
    int k = 10;
    int count = 0;
    while (k < 10) {
        count++;
        k++;
    }
    System.out.println(count);
    Show answer

    Answer: B. The Boolean expression of a while loop is evaluated before the first iteration. 10 < 10 is false at the start, so the body runs zero times and count stays 0. Answering 1 treats the loop as if it always runs once, and the loop cannot be infinite because it never starts.

  3. 3 Each of the following code segments declares int i and contains a while loop. Which code segment contains an infinite loop? 2.7.A.2
    Show answer

    Answer: D. Starting at 1 and adding 2 gives only odd numbers (1, 3, 5, 7, 9, 11...), so i != 10 is always true and the loop never ends. The i < 10 loop stops at 12, the i > 0 loop stops at -2, and the i != 12 loop reaches exactly 12 (0, 4, 8, 12) and stops.

  4. 4 The following code segment is intended to print the sum of the integers from 1 to n, inclusive. For n = 5 it should print 15, but it prints 10. Which change makes the code segment work as intended? 2.7.A.4
    int n = 5;
    int sum = 0;
    int i = 1;
    while (i < n) {
        sum += i;
        i++;
    }
    System.out.println(sum);
    Show answer

    Answer: A. The loop stops one time too early, an off by one error: 5 is never added. With i <= n the last iteration adds 5, giving 15. Starting at 0 only adds an extra 0 (still 10), and swapping the two statements adds 2 + 3 + 4 + 5 = 14.

  5. 5 Consider the following code segment. What is printed as a result of executing the code segment? 2.7.A.1, 2.7.B.1
    int n = 20;
    while (n % 6 != 0) {
        n++;
    }
    System.out.println(n);
    Show answer

    Answer: C. The loop repeats while n is not a multiple of 6: 20, 21, 22 and 23 all leave a remainder, and at 24 the remainder is 0, so the loop ends. 18 is a multiple of 6 but is smaller than the start value, and the loop only counts up. 20 would print only if the body never ran.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • How many times a while loop body can run three cases CED 2.7.A.1, 2.7.A.2, 2.7.A.3
    1. zero timesthe Boolean expression is false at the start
    2. some number of timesit becomes false after some iterations
    3. forever (infinite loop)it always evaluates to true
  • Kinds of off by one error two kinds CED 2.7.A.4
    1. one iteration too many
    2. one iteration too few

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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure