Iteration: When Loops Are Needed and How They Go Wrong
What iteration does, how to recognize problems that need it, why a loop can run zero times, and the two classic loop errors: infinite loops and off by one errors.
Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true. If that expression is false at the start, the loop body never runs. If it can never become false, the result is an infinite loop. And if the loop runs one time too many or one time too few, it has an off by one error. Recognizing these three behaviors is the foundation for writing every loop correctly.
1What Iteration Does
Selection decides whether code runs; iteration decides how many times. An iteration statement, or loop, has a Boolean expression that controls it and a body of statements to repeat. Each time the expression is true, the body runs once, and then the expression is checked again. When the expression becomes false, the loop ends and the program continues with the statement after it.
Each run of the body is called an iteration or a pass. For a loop to finish, something in the body must eventually make the Boolean expression false, usually by changing a variable that appears in it. In the loop of Figure 1, the body increases count by 1 each pass, so count <= 5 eventually fails.
Java has two loop statements, while and for. This guide uses while, which states the controlling Boolean expression most directly; the ideas apply to both.
true.| Situation | Number of times the body runs | Example |
|---|---|---|
| Condition true several times, then false | One or more | count from 1 while count <= 5: 5 times |
| Condition false at the first check | Zero | count is 10, condition count < 5 |
| Condition never becomes false | Forever (infinite loop) | n != 10 while n goes 0, 3, 6, 9, 12, … |
Repeating Without Copying Code
Print the whole numbers 1 through 5. Compare writing five statements with using a loop.
int count = 1;
while (count <= 5)
{
System.out.println(count);
count = count + 1;
}
1
2
3
4
5
- 1Without a loop you would write five nearly identical
printlnstatements, and 500 for 1 through 500. - 2With a loop the repeated work, print then increase, is written once.
- 3The condition
count <= 5is checked before each pass; after printing 5,countbecomes 6 and the check isfalse.
2Recognizing When a Loop Is Needed
An iterative process is required whenever the same steps must happen repeatedly to achieve a result. Two signals are especially strong. The first is a large or variable number of repetitions: printing 500 labels, or processing however many values a file contains. The second is repetition until a goal is reached, when the number of repetitions is not known in advance: doubling a balance until it reaches a target, or asking again until a valid answer arrives.
Writing the same statement several times in a row is a sign that a loop would be better. Loops make code shorter, and more importantly they make it general: changing a single number changes how many times the work is done, without rewriting anything else. Problems described with words such as "each," "every," "until," "while," or "how many" usually call for iteration.
How Many Doublings?
A savings balance starts at 50 and doubles each year. How many years until it reaches at least 1000?
int balance = 50;
int years = 0;
while (balance < 1000)
{
balance = balance * 2;
years = years + 1;
}
System.out.println(years + " years, balance " + balance);
5 years, balance 1600
- 1Unknown repetition count. We do not know the number of years in advance, which is exactly when a loop is needed.
- 2Each pass doubles the balance and counts a year: 100, 200, 400, 800, 1600.
- 3Stopping. After the fifth pass the balance is 1600, and
1600 < 1000isfalse.
| Pass | balance before | balance < 1000? | balance after | years |
|---|---|---|---|---|
| 1 | 50 | true | 100 | 1 |
| 2 | 100 | true | 200 | 2 |
| 3 | 200 | true | 400 | 3 |
| 4 | 400 | true | 800 | 4 |
| 5 | 800 | true | 1600 | 5 |
| (check) | 1600 | false: stop | 5 |
An if statement checks its condition once and runs its body at most once. If the task is "keep doubling until the balance reaches 1000," an if doubles it once and stops. Repetition until a goal is reached requires a loop.
3Loops That Run Zero Times
The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false. The check comes before each pass, including the first, so a loop whose condition is false from the start skips its body completely and the program moves on as if the loop were not there.
This is usually correct behavior rather than a bug. A loop that processes the items in a list should do nothing when the list is empty; a loop that doubles a balance until it reaches 1000 should do nothing if the balance is already 1000 or more. When tracing, always evaluate the condition before the first pass, and do not assume the body runs at least once.
false.A Loop Whose Body Never Runs
Predict the output.
int count = 10;
while (count < 5)
{
System.out.println("inside: " + count);
count = count + 1;
}
System.out.println("after: " + count);
after: 10
- 1The first check.
10 < 5isfalse. - 2The body is skipped entirely; nothing inside it runs, so
countis never changed.
4Infinite Loops
An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true. The program never leaves the loop: it may print endlessly, or appear to freeze. Infinite loops are logic errors; the code compiles and starts running normally, and the problem shows only at run time.
The usual causes are a loop variable that is never updated, a variable that moves away from the stopping value instead of toward it, and a stopping test that can be stepped over. The last is easy to miss: while (n != 10) never ends if n goes 0, 3, 6, 9, 12, because n is never exactly 10. A condition written with < or >, such as n < 10, stops as soon as the variable passes the boundary.
true.| Cause of an infinite loop | Example | Fix |
|---|---|---|
| The loop variable is never changed | while (count <= 5) { println(count); } | Update the variable inside the body |
| The variable moves the wrong way | while (count <= 5) { count = count - 1; } | Move toward the stopping value |
| The target can be stepped over | while (n != 10) { n = n + 3; } | Use < or > instead of != |
| A stray semicolon after the condition | while (count <= 5); { ... } | Remove the semicolon |
Watching a Loop Skip Its Target
The loop while (n != 10) { n = n + 3; } starting from 0 never ends. This version prints the first six values of n to show why.
int n = 0;
int shown = 0;
while (shown < 6)
{
System.out.println(n + " (n != 10 is " + (n != 10) + ")");
n = n + 3;
shown = shown + 1;
}
0 (n != 10 is true)
3 (n != 10 is true)
6 (n != 10 is true)
9 (n != 10 is true)
12 (n != 10 is true)
15 (n != 10 is true)
- 1The values of
ngo 0, 3, 6, 9, 12, 15, … They jump from 9 straight to 12. - 2
n != 10istrueevery time, so the original loop would never stop. - 3The fix. Use a condition that cannot be stepped over:
while (n < 10)stops as soon asnreaches 12.
n != 10 equal to true, which is why the original loop is infinite. Prefer < or > over != when a variable moves in steps.A loop such as while (count <= 5) { System.out.println(count); } prints 1 forever, because nothing in the body changes count. Every loop body must make progress toward making the condition false.
5Off by One Errors
Off by one errors occur when the iteration statement loops one time too many or one time too few. They usually come from the boundary of the Boolean expression, using < where <= was needed or the reverse, or from starting the loop variable at the wrong value, such as 0 instead of 1.
These errors are common because both versions look reasonable and both compile. The way to catch them is to check the edges explicitly: what is the value of the loop variable on the first pass, what is it on the last pass, and how many passes is that in total? For a variable that goes from a to b in steps of 1, inclusive, the body runs b - a + 1 times.
One Pass Too Few
The goal is to print 1 through 5. Compare the two loops.
int count = 1;
while (count < 5)
{
System.out.println(count);
count = count + 1;
}
1
2
3
4
int count = 1;
while (count <= 5)
{
System.out.println(count);
count = count + 1;
}
1
2
3
4
5
- 1
count < 5. Whencountreaches 5, the check isfalse, so 5 is never printed: four passes. - 2
count <= 5. 5 passes the check, so it is printed; then 6 fails: five passes. - 3Check the last pass. Ask what the variable equals on the final iteration and whether that pass should happen.
< where <= was needed is the classic off by one error.A Sum That Misses a Term
Both loops are meant to add 1 + 2 + … + 10, which is 55. Predict each result.
int sum = 0;
int k = 1;
while (k < 10)
{
sum = sum + k;
k = k + 1;
}
System.out.println(sum);
45
int sum = 0;
int k = 0;
while (k <= 10)
{
sum = sum + k;
k = k + 1;
}
System.out.println(sum);
55
- 1First loop.
kruns 1 to 9; the 10 is never added: 45. - 2Second loop. It runs 11 times, for
kfrom 0 to 10. The extra pass adds 0, which happens not to change the total: 55. - 3Lesson. Count the passes and list the first and last values of the loop variable; an extra or missing pass is not always visible in the result.
A loop that adds 0 on an extra pass gives the right total by luck. A loop that prints one extra line or processes one extra value may not. Check the first and last values of the loop variable directly instead of relying on the final answer to look right.
6Checking a Loop Before Trusting It
Three quick questions catch most loop errors. First: is the condition true at the start, and if not, is skipping the body acceptable? Second: does every pass move the loop variable toward making the condition false, so the loop must end? Third: what are the values of the loop variable on the first and last passes, and is that the right number of passes?
Tracing with a table, one row per pass with the condition's value and each variable's value, answers all three questions at once. For loops with many passes, trace the first two passes and the last two; the middle passes usually behave the same way, and the errors live at the edges.
while (count <= 5); gives the loop an empty body. If the condition is true, the loop repeats nothing forever, because the block that was meant to update count sits after the loop and never runs. Never put a semicolon directly after a loop header.
Four Habits for Correct Loops
1. Check Before Every Pass
Including the first: a loop may run zero times.
2. Make Progress
Each pass must move toward making the condition false.
3. Avoid != for Steps
Use < or > so the target cannot be skipped.
4. Check First and Last
Count the passes to catch off by one errors.
Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true. An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true. The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false. Off by one errors occur when the iteration statement loops one time too many or one time too few.