Sub topic 9
Trace loops and prevent boundary and termination errors
A loop repeats a group of statements called its body. An iteration is one pass through that body. To check that a loop works, you can trace it: follow each step and write down how its values change.
A trace helps answer three questions:
- Does the loop visit the values you expect?
- Does it stop at the right point?
- Does it stop at all?
Trace a loop step by step
A condition is a test that is either true or false. In a for loop, Java checks the condition before each iteration. If it is true, Java runs the body and then performs the update. If it is false, the loop ends.
An array is a fixed-size collection of values. An index is a value’s position in an array. The first index is 0, not 1.
Save this program as LoopTrace.java:
public class LoopTrace {
public static void main(String[] args) {
int[] values = {4, 7, 9};
int sum = 0;
for (int i = 0; i < values.length; i++) {
sum += values[i];
System.out.println(
"i=" + i + ", value=" + values[i] + ", sum=" + sum
);
}
System.out.println("Final sum: " + sum);
}
}Compile and run it with these commands:
javac LoopTrace.java
java LoopTraceThe expression values.length gives the number of items in the array. Here it is 3. The update i++ adds 1 to i after each pass.
Trace the loop in this order: check the condition, run the body if the condition is true, and then update i.
| `i` at the test | Is `i < 3` true? | Value added | `sum` after the body |
|---|---|---|---|
| 0 | Yes | 4 | 4 |
| 1 | Yes | 7 | 11 |
| 2 | Yes | 9 | 20 |
| 3 | No | None | 20 |
At i = 3, the condition is false. The body does not run again, so the program prints a final sum of 20.
Check the boundaries
A boundary is an edge of the range a loop should visit. In the example, the valid array indexes are 0, 1, and 2. The array has three items, but its last index is 2.
An off-by-one error happens when a loop starts or stops one step too early or too late. If the example used i <= values.length, the condition would still be true at i = 3. The body would try to read values[3], which does not exist. Java would throw an ArrayIndexOutOfBoundsException, an error that stops this program.
For a loop that visits every array item by index, start at 0 and keep going while the index is less than the array length.
Also check an empty array. Its length is 0, so i < values.length is false on the first test. The body runs zero times. That is the right result: there are no items to visit.
Check that the loop can stop
Termination means that a loop ends. An infinite loop keeps repeating instead of reaching its end.
For a condition-controlled loop, look for a change that can make the condition false. In the example, i starts at 0, increases by 1, and eventually reaches 3. Then i < values.length is false.
If i never changed, the condition would stay true and the loop would repeat forever. Moving in the wrong direction can cause the same problem. For example, if i starts at 0 and decreases while the condition is i < 3, it moves away from the stopping point.
Account for the loop type
A while loop also tests its condition before the body. Check that the body changes something the condition depends on, unless another action ends the loop.
A do-while loop tests its condition after the body. Its body runs at least once, even if the condition is false at the start. This matters when an array might be empty: do not read its first item in a do-while body unless you have checked that the item exists.
The break statement exits the nearest loop immediately. The continue statement skips the rest of the current iteration. Both can change a trace.
In a basic for loop, continue goes to the update before the next condition test. In a while loop, it goes to the next condition test. If a while loop puts its only update after continue, that update is skipped on that pass. The loop may then repeat forever.
Trace nested loops
A nested loop is a loop inside another loop. Trace the inner loop to completion for each pass of the outer loop. Check the start and end values of both loops.
For example, suppose an outer loop visits rows 0 and 1, and an inner loop visits columns 0, 1, and 2. The inner loop visits three columns for each row, for six visits in total. A break inside the inner loop exits that inner loop, not the outer one. A continue inside it skips only the rest of the current inner iteration.
Practice
Exercise
An array has five items. A loop starts at index 0 and increases the index by 1. What condition lets it visit every item without going past the end?
Show answer
Use an index less than 5, or less than the array’s length. The visited indexes are 0 through 4.
Exercise
A while loop starts with count equal to 0. Its condition is count < 3. The body runs continue before the only count++ statement. Does it stop?
Show answer
No. The update is skipped, so count stays 0 and the condition remains true. Move the update so it runs before continue, or use a suitable for loop.
Exercise
A do-while loop has a condition that is false before its first pass. How many times does its body run?
Show answer
Once. A do-while loop tests the condition after running its body.