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.
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.
1The 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.
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 |
A Decreasing Counter
Predict the output.
int seconds = 5;
while (seconds > 0)
{
System.out.println(seconds);
seconds = seconds - 1;
}
System.out.println("Liftoff");
5
4
3
2
1
Liftoff
- 1Initialization.
secondsstarts at 5. - 2Each pass prints the current value and then decreases it by 1.
- 3Termination. After printing 1,
secondsbecomes 0 and0 > 0isfalse. The loop ends and "Liftoff" prints.
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.
2Step 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.
true, the loop body is executed. This continues until the expression evaluates to false, whereupon the iteration terminates.Growing Text Until It Is Long Enough
Predict the output.
String bar = "";
while (bar.length() < 5)
{
bar = bar + "*";
}
System.out.println(bar);
System.out.println(bar.length());
*****
5
- 1Condition from a method call.
bar.length() < 5is re-evaluated before every pass, using the current string. - 2Each pass builds a new string one star longer.
- 3Termination. When the length reaches 5, the condition is
false.
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.
3Counting 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.
while loops follow one of a few patterns: counting, accumulating a result, or repeating until a goal is reached.Adding Up a Sequence
Compute 1 + 2 + … + 100 and count the passes.
int k = 1;
int total = 0;
while (k <= 100)
{
total = total + k;
k = k + 1;
}
System.out.println(total);
System.out.println(k);
5050
101
- 1Accumulator.
totalstarts at 0, and each pass adds the currentk. - 2Passes.
ktakes the values 1 through 100, so the body runs 100 times. - 3After the loop,
kis 101: the first value for whichk <= 100isfalse.
| 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; |
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.
4Repeating 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.
while loop suits processes that repeat until a condition changes, even when the number of passes is not obvious in advance.How Many Times Can 100 Be Halved?
Predict the output.
int n = 100;
int halvings = 0;
while (n >= 1)
{
n = n / 2;
halvings = halvings + 1;
}
System.out.println(halvings + " " + n);
7 0
- 1Values after each pass. 50, 25, 12, 6, 3, 1, 0 (integer division drops remainders).
- 2Seven passes. After the seventh,
nis 0 and0 >= 1isfalse.
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.
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);
8
- 1The sequence. 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
- 2Counting. Each arrow is one pass: 8 passes.
- 3Why
while. There is no simple formula for the number of steps, so the loop simply repeats until the conditionn != 1becomesfalse. Here!=is safe because the process lands exactly on 1.
while loop is the natural choice when the number of passes is discovered by running the process, not known beforehand.5Tracing 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 |
Two Variables Moving Toward Each Other
Trace the loop and predict the output.
int x = 1;
int y = 20;
while (x < y)
{
x = x * 2;
y = y - 3;
}
System.out.println(x + " " + y);
16 8
- 1Check 1: 1 < 20 → x = 2, y = 17.
- 2Check 2: 2 < 17 → x = 4, y = 14.
- 3Check 3: 4 < 14 → x = 8, y = 11.
- 4Check 4: 8 < 11 → x = 16, y = 8.
- 5Check 5: 16 < 8 is
false: the loop ends.
6Variables 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.
A Variable Declared Inside the Loop
Explain the compile error.
int count = 1;
while (count <= 3)
{
int doubled = count * 2;
count = count + 1;
}
System.out.println(doubled);
- 1Scope.
doubledis declared inside the loop body, so it exists only within those braces. - 2After the loop the name no longer refers to anything, and the compiler reports that it cannot find the symbol.
- 3Fix. Declare
doubledbefore the loop if its value is needed afterward.
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.
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.