---
title: "while Loop Processes | FiveStudy"
description: "Prime, test, work, advance: sentinel runs and goal-driven processes where the pass count is unknown."
url: https://fivestudy.com/guides/while-loop-processes
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# while Loop Processes

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Selection and Iteration

AP® Computer Science A · Selection and Iteration

# *while* Loops

How the while loop works step by step, how to trace it with a table, and the standard patterns it is used for: counting, accumulating a result, and repeating a process until a goal is reached.

1. The while Statement 2. Step by Step 3. Counting and Accumulating 4. Repeating Until a Goal 5. Tracing Loops 6. Variables and Loops

Big Picture

A `while` loop is a type of iterative statement. In `while` loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to `true`, the loop body is executed. This continues until the Boolean expression evaluates to `false`, whereupon the iteration terminates. A correct `while` loop has three working parts: an initialization before the loop, a Boolean expression in the header, and an update in the body that moves toward making the expression false.

## 1 The while Statement

A `while` loop is written as the keyword `while`, a Boolean expression in parentheses, and a body in braces: `while (count <= 3) { ... }`. It reads naturally: *while* this is true, keep doing that. The body may contain any statements, including selection statements and other loops.

The variables the condition depends on are usually given starting values before the loop, in an **initialization**. Inside the body, an **update** changes at least one of those variables so that the condition eventually becomes `false`. Without an initialization, the first check may use an unintended value; without an update, the loop never ends.

Choosing the condition is the heart of writing a `while` loop. State, in words, when the loop should *keep going*, not when it should stop, and translate that sentence into a Boolean expression. "Keep going while there is time left" becomes `seconds > 0`. If the rule is naturally stated as a stopping condition, such as "stop when the balance reaches 1000," negate it to get the continuing condition: `balance < 1000`.

**Figure 1.** A `while` loop is a type of iterative statement. Its Boolean expression is evaluated before each iteration of the loop body, including the first.

| Part | Where it appears | When it runs |
| --- | --- | --- |
| Initialization | Before the loop | Once |
| Boolean expression | In the `while (...)` header | Before every pass, including the first, and once more when it fails |
| Loop body | In braces after the header | Each time the expression is true |
| Update | Inside the body | Each pass; it must move toward making the expression false |

Worked Example 1 Counting down

### A Decreasing Counter

Predict the output.

Code

```
int seconds = 5;
while (seconds > 0)
{
    System.out.println(seconds);
    seconds = seconds - 1;
}
System.out.println("Liftoff");
```

Output

```
5
4
3
2
1
Liftoff
```

1. 1 **Initialization.** `seconds` starts at 5.
2. 2 **Each pass** prints the current value and then decreases it by 1.
3. 3 **Termination.** After printing 1, `seconds` becomes 0 and `0 > 0` is `false`. The loop ends and "Liftoff" prints.

**Result:** The program prints 5, 4, 3, 2, 1, Liftoff. The update can decrease the variable as well as increase it, as long as it moves toward making the condition false.

Common Mistake 1 · Placing the Update Outside the Braces

If the update statement is written after the closing brace, it is not part of the body. The condition never changes inside the loop, and the loop repeats forever. Keep the update inside the braces, usually as the last statement of the body.

## 2 Step by Step

The Boolean expression is evaluated before each iteration of the loop body, including the first. If it is `true`, the entire body runs from top to bottom, and then control returns to the header for another check. If it is `false`, the iteration terminates and execution continues with the statement after the loop.

Two consequences follow. First, the body may run zero times, if the expression is false at the very first check. Second, the expression is always checked one more time than the body runs: a loop that makes three passes performs four checks, and the last check is the one that fails. The condition is not monitored during the body; if a variable briefly makes it false in the middle of a pass, the pass still finishes.

The order of statements inside the body matters as well. In a counting loop that prints and then updates, the first value printed is the starting value; if the update comes first, the first value printed is one step later, and the last value printed is one step past the intended end. When a loop's output starts or ends one value off, check the order of the statements in the body as well as the condition.

**Figure 2.** When the expression evaluates to `true`, the loop body is executed. This continues until the expression evaluates to `false`, whereupon the iteration terminates.

Worked Example 2 Building a string

### Growing Text Until It Is Long Enough

Predict the output.

Code

```
String bar = "";
while (bar.length() < 5)
{
    bar = bar + "*";
}
System.out.println(bar);
System.out.println(bar.length());
```

Output

```
*****
5
```

1. 1 **Condition from a method call.** `bar.length() < 5` is re-evaluated before every pass, using the current string.
2. 2 **Each pass** builds a new string one star longer.
3. 3 **Termination.** When the length reaches 5, the condition is `false`.

**Result:** The output is ***** and 5. Any Boolean expression can control a loop, including one that calls a method on an object that the body changes or replaces.

Common Mistake 2 · Expecting the Loop to Stop Mid-Pass

A `while` loop checks its condition only at the top of each pass. If a statement in the middle of the body makes the condition false, the rest of the body still runs before the next check ends the loop.

## 3 Counting and Accumulating

The most common `while` loop is a **counting loop**: a counter starts at a value, the condition tests whether it has passed an end value, and the body updates it by 1. For a counter that goes from `a` to `b` inclusive, the body runs `b - a + 1` times, and after the loop the counter holds the first value that failed the test.

Counting loops often carry an **accumulator**, a variable that builds up a result across passes. A running total starts at 0 and adds a value each pass; a running product starts at 1 and multiplies. The accumulator must be initialized before the loop, not inside it, or it would be reset on every pass.

Counting how many values meet a condition combines both ideas: a counter-controlled loop visits the values, and an `if` inside the body increases a second counter only when the condition holds. That pattern, along with finding a maximum or minimum, forms the standard numeric algorithms built from loops and selection.

**Figure 3.** Most `while` loops follow one of a few patterns: counting, accumulating a result, or repeating until a goal is reached.

Worked Example 3 Accumulating

### Adding Up a Sequence

Compute 1 + 2 + … + 100 and count the passes.

Code

```
int k = 1;
int total = 0;
while (k <= 100)
{
    total = total + k;
    k = k + 1;
}
System.out.println(total);
System.out.println(k);
```

Output

```
5050
101
```

1. 1 **Accumulator.** `total` starts at 0, and each pass adds the current `k`.
2. 2 **Passes.** `k` takes the values 1 through 100, so the body runs 100 times.
3. 3 **After the loop,** `k` is 101: the first value for which `k <= 100` is `false`.

**Result:** The program prints 5050 and 101. After a counting loop ends, the loop variable holds the first value that failed the condition, not the last value used.

| Pattern | Typical condition | Typical update |
| --- | --- | --- |
| Count up from a to b | `k <= b` | `k = k + 1;` |
| Count down to 1 | `k > 0` | `k = k - 1;` |
| Accumulate a total | Any counting condition | `total = total + value;` plus the counter update |
| Repeat until a goal | `balance < goal` | A step toward the goal, such as `balance = balance * 2;` |

Common Mistake 3 · Initializing the Accumulator Inside the Loop

Writing `int total = 0;` inside the body resets the total on every pass, and it cannot be used after the loop anyway. Declare and initialize accumulators before the loop begins.

## 4 Repeating Until a Goal

Many processes repeat an unknown number of times: halving a value until it reaches 0, doubling a balance until it reaches a target, applying a rule until a sequence reaches 1. The `while` loop handles these directly, because its condition describes the goal rather than a count. The loop keeps going exactly as long as the goal has not been reached.

For such loops, the key question is whether the process is guaranteed to reach the goal. Repeated integer halving always reaches 0; doubling a positive balance always passes any target. When the stopping test uses `!=`, be sure the variable lands exactly on the stopping value, as the 3n + 1 process lands on 1, rather than jumping past it.

**Figure 4.** A `while` loop suits processes that repeat until a condition changes, even when the number of passes is not obvious in advance.

Worked Example 4 Halving

### How Many Times Can 100 Be Halved?

Predict the output.

Code

```
int n = 100;
int halvings = 0;
while (n >= 1)
{
    n = n / 2;
    halvings = halvings + 1;
}
System.out.println(halvings + " " + n);
```

Output

```
7 0
```

1. 1 **Values after each pass.** 50, 25, 12, 6, 3, 1, 0 (integer division drops remainders).
2. 2 **Seven passes.** After the seventh, `n` is 0 and `0 >= 1` is `false`.

**Result:** The output is 7 0. Integer division guarantees that repeated halving reaches 0, so the loop always ends.

Worked Example 5 Unknown number of passes

### Counting Steps to Reach 1

Start with 6. If the number is even, halve it; if odd, multiply by 3 and add 1. Count the steps until it reaches 1.

Code

```
int n = 6;
int steps = 0;
while (n != 1)
{
    if (n % 2 == 0)
    {
        n = n / 2;
    }
    else
    {
        n = 3 * n + 1;
    }
    steps = steps + 1;
}
System.out.println(steps);
```

Output

```
8
```

1. 1 **The sequence.** 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
2. 2 **Counting.** Each arrow is one pass: 8 passes.
3. 3 **Why `while`.** There is no simple formula for the number of steps, so the loop simply repeats until the condition `n != 1` becomes `false`. Here `!=` is safe because the process lands exactly on 1.

**Result:** The program prints 8. A `while` loop is the natural choice when the number of passes is discovered by running the process, not known beforehand.

## 5 Tracing while Loops

Predicting the result of a loop requires tracing it. Make a table with a row for each check of the Boolean expression and a column for each variable. In each row, record the variable values at the check, whether the expression is `true`, and the values after the body runs. Stop at the row where the expression is `false`; the values in that row are the values after the loop.

Tracing is slower than guessing, but it is the only reliable method when several variables change in different ways in the same pass. It also exposes the two classic loop errors: a row where nothing changes signals an infinite loop, and a first or last row that is not what you expected signals an off by one error.

| Check | x | y | x < y | After the body |
| --- | --- | --- | --- | --- |
| 1 | 1 | 20 | true | x = 2, y = 17 |
| 2 | 2 | 17 | true | x = 4, y = 14 |
| 3 | 4 | 14 | true | x = 8, y = 11 |
| 4 | 8 | 11 | true | x = 16, y = 8 |
| 5 | 16 | 8 | false | loop ends |

Worked Example 6 Tracing

### Two Variables Moving Toward Each Other

Trace the loop and predict the output.

Code

```
int x = 1;
int y = 20;
while (x < y)
{
    x = x * 2;
    y = y - 3;
}
System.out.println(x + " " + y);
```

Output

```
16 8
```

1. 1 **Check 1:** 1 < 20 → x = 2, y = 17.
2. 2 **Check 2:** 2 < 17 → x = 4, y = 14.
3. 3 **Check 3:** 4 < 14 → x = 8, y = 11.
4. 4 **Check 4:** 8 < 11 → x = 16, y = 8.
5. 5 **Check 5:** 16 < 8 is `false`: the loop ends.

**Result:** The output is 16 8. A trace table with one row per check is the most reliable way to follow a loop whose variables change in different ways.

## 6 Variables and Loops

Where a variable is declared determines where it can be used. A variable declared inside the loop body exists only within those braces; it is created fresh on each pass and is gone when the loop ends. Counters, accumulators, and any value needed after the loop must therefore be declared before it.

Variables declared inside the body are useful for temporary values that matter only within one pass, such as an intermediate calculation. Keeping such values local makes the loop easier to understand, because a reader can see that they do not carry information from one pass to the next.

Worked Example 7 Scope

### A Variable Declared Inside the Loop

Explain the compile error.

Code that does not compile

```
int count = 1;
while (count <= 3)
{
    int doubled = count * 2;
    count = count + 1;
}
System.out.println(doubled);
```

1. 1 **Scope.** `doubled` is declared inside the loop body, so it exists only within those braces.
2. 2 **After the loop** the name no longer refers to anything, and the compiler reports that it cannot find the symbol.
3. 3 **Fix.** Declare `doubled` before the loop if its value is needed afterward.

**Result:** The program does not compile. Variables declared inside a loop body are created fresh on each pass and cannot be used after the loop ends.

Common Mistake 4 · Using a Loop-Body Variable After the Loop

A variable declared inside the braces of a loop no longer exists after the closing brace, so using it there does not compile. If a value computed in the loop is needed later, declare the variable before the loop and assign it inside.

### Four Habits for while Loops

#### 1. Initialize, Check, Update

Every while loop needs all three.

#### 2. One More Check Than Passes

The final check is the one that fails.

#### 3. Accumulators Before the Loop

Otherwise they reset every pass.

#### 4. Trace With a Table

One row per check; stop at the first false.

Core Synthesis

A `while` loop is a type of iterative statement. In `while` loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to `true`, the loop body is executed. This continues until the Boolean expression evaluates to `false`, whereupon the iteration terminates. Loops are typically built from an initialization before the loop, the Boolean expression that controls it, and an update in the body that moves toward making that expression false.

FiveStudy AP® Computer Science A Study Guide · Selection and Iteration · while Loops Back to top ↑
