# AP® Computer Science A 2.7 while Loops

Source: https://lockincs.com/ap-csa/unit-2/2-7-while-loops/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 2.7.A, 2.7.A.1, 2.7.A.2, 2.7.A.3, 2.7.A.4, 2.7.B, 2.7.B.1

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.

## What you will learn

- 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.

## 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.

## Common mix-ups

- Not true: A while loop always runs at least once. The Boolean expression is checked before the first iteration. If it is false at the start, the body runs zero times.
- Not true: The loop stops the moment the condition becomes false, even in the middle of the body. The condition is only checked at the top, before each iteration. Once the body starts, every statement in it runs before the next check.
- Not true: An infinite loop is a compile error. It compiles. It is a logic error: the program keeps running because the Boolean expression never becomes false.

## 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.

## Checkpoint: 5 practice questions

### Question 1

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int n = 1;
int sum = 0;
while (sum < 20) {
    sum += n;
    n += 2;
}
System.out.println(n + " " + sum);
```

- A. 9 16
- B. 9 25
- C. 11 36
- D. 11 25

**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.

### Question 2

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int k = 10;
int count = 0;
while (k < 10) {
    count++;
    k++;
}
System.out.println(count);
```

- A. 1
- B. 0
- C. 10
- D. Nothing is printed because the loop never ends.

**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.

### Question 3

Each of the following code segments declares `int i` and contains a `while` loop. Which code segment contains an infinite loop?

- A. `int i = 0; while (i < 10) { i += 3; }`
- B. `int i = 10; while (i > 0) { i -= 3; }`
- C. `int i = 0; while (i != 12) { i += 4; }`
- D. `int i = 1; while (i != 10) { i += 2; }`

**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.

### Question 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?

```java
int n = 5;
int sum = 0;
int i = 1;
while (i < n) {
    sum += i;
    i++;
}
System.out.println(sum);
```

- A. Change `i < n` to `i <= n`
- B. Change `int i = 1;` to `int i = 0;`
- C. Change `i++;` to `i += 2;`
- D. Swap the order of `sum += i;` and `i++;`

**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.

### Question 5

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int n = 20;
while (n % 6 != 0) {
    n++;
}
System.out.println(n);
```

- A. 20
- B. 18
- C. 24
- D. 21

**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.

## 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.

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
