AP Computer Science A · Study guide

Iteration Need and Loop Errors

AP® Computer Science A · Selection and Iteration

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.

Big Picture

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.

Figure 1. 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.
SituationNumber of times the body runsExample
Condition true several times, then falseOne or morecount from 1 while count <= 5: 5 times
Condition false at the first checkZerocount is 10, condition count < 5
Condition never becomes falseForever (infinite loop)n != 10 while n goes 0, 3, 6, 9, 12, …
Worked Example 1 Why iterate

Repeating Without Copying Code

Print the whole numbers 1 through 5. Compare writing five statements with using a loop.

Code
int count = 1;
while (count <= 5)
{
    System.out.println(count);
    count = count + 1;
}
Output
1
2
3
4
5
  1. 1Without a loop you would write five nearly identical println statements, and 500 for 1 through 500.
  2. 2With a loop the repeated work, print then increase, is written once.
  3. 3The condition count <= 5 is checked before each pass; after printing 5, count becomes 6 and the check is false.
Result: The program prints 1 through 5, one per line. Iteration is needed whenever a step must repeat many times, or a number of times that is not known in advance.

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.

Worked Example 2 Repeating until a goal

How Many Doublings?

A savings balance starts at 50 and doubles each year. How many years until it reaches at least 1000?

Code
int balance = 50;
int years = 0;
while (balance < 1000)
{
    balance = balance * 2;
    years = years + 1;
}
System.out.println(years + " years, balance " + balance);
Output
5 years, balance 1600
  1. 1Unknown repetition count. We do not know the number of years in advance, which is exactly when a loop is needed.
  2. 2Each pass doubles the balance and counts a year: 100, 200, 400, 800, 1600.
  3. 3Stopping. After the fifth pass the balance is 1600, and 1600 < 1000 is false.
Result: The output is 5 years, balance 1600. The loop repeats as long as the goal has not been reached, then stops.
Passbalance beforebalance < 1000?balance afteryears
150true1001
2100true2002
3200true4003
4400true8004
5800true16005
(check)1600false: stop5
Common Mistake 1 · Using if Where a Loop Is Needed

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.

Figure 2. The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
Worked Example 3 Zero iterations

A Loop Whose Body Never Runs

Predict the output.

Code
int count = 10;
while (count < 5)
{
    System.out.println("inside: " + count);
    count = count + 1;
}
System.out.println("after: " + count);
Output
after: 10
  1. 1The first check. 10 < 5 is false.
  2. 2The body is skipped entirely; nothing inside it runs, so count is never changed.
Result: The output is only after: 10. A loop whose condition is false at the start executes its body zero times.

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.

Figure 3. An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
Cause of an infinite loopExampleFix
The loop variable is never changedwhile (count <= 5) { println(count); }Update the variable inside the body
The variable moves the wrong waywhile (count <= 5) { count = count - 1; }Move toward the stopping value
The target can be stepped overwhile (n != 10) { n = n + 3; }Use < or > instead of !=
A stray semicolon after the conditionwhile (count <= 5); { ... }Remove the semicolon
Worked Example 4 Infinite loops

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.

Code
int n = 0;
int shown = 0;
while (shown < 6)
{
    System.out.println(n + "  (n != 10 is " + (n != 10) + ")");
    n = n + 3;
    shown = shown + 1;
}
Output
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)
  1. 1The values of n go 0, 3, 6, 9, 12, 15, … They jump from 9 straight to 12.
  2. 2n != 10 is true every time, so the original loop would never stop.
  3. 3The fix. Use a condition that cannot be stepped over: while (n < 10) stops as soon as n reaches 12.
Result: Every value printed has n != 10 equal to true, which is why the original loop is infinite. Prefer < or > over != when a variable moves in steps.
Common Mistake 2 · Forgetting to Update the Loop Variable

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.

Figure 4. Off by one errors occur when the iteration statement loops one time too many or one time too few.
Worked Example 5 Off by one

One Pass Too Few

The goal is to print 1 through 5. Compare the two loops.

Condition count < 5
int count = 1;
while (count < 5)
{
    System.out.println(count);
    count = count + 1;
}
Output
1
2
3
4
Condition count <= 5
int count = 1;
while (count <= 5)
{
    System.out.println(count);
    count = count + 1;
}
Output
1
2
3
4
5
  1. 1count < 5. When count reaches 5, the check is false, so 5 is never printed: four passes.
  2. 2count <= 5. 5 passes the check, so it is printed; then 6 fails: five passes.
  3. 3Check the last pass. Ask what the variable equals on the final iteration and whether that pass should happen.
Result: The first loop prints 1 to 4; the second prints 1 to 5. Choosing < where <= was needed is the classic off by one error.
Worked Example 6 Off by one in a total

A Sum That Misses a Term

Both loops are meant to add 1 + 2 + … + 10, which is 55. Predict each result.

k < 10
int sum = 0;
int k = 1;
while (k < 10)
{
    sum = sum + k;
    k = k + 1;
}
System.out.println(sum);
Output
45
k from 0 to 10
int sum = 0;
int k = 0;
while (k <= 10)
{
    sum = sum + k;
    k = k + 1;
}
System.out.println(sum);
Output
55
  1. 1First loop. k runs 1 to 9; the 10 is never added: 45.
  2. 2Second loop. It runs 11 times, for k from 0 to 10. The extra pass adds 0, which happens not to change the total: 55.
  3. 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.
Result: The first loop gives 45, one term short; the second gives the correct 55 even though it makes one extra pass. Checking the first and last values of the loop variable catches both kinds of off by one error.
Common Mistake 3 · Assuming the Result Reveals Every Off by One Error

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.

Common Mistake 4 · Putting a Semicolon After the Loop Condition

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.

Core Synthesis

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.