Sub topic 9
Trace loops and prevent boundary and termination errors
A loop can look correct and still run too many times, skip a value, or never stop. To check it, you can follow its values one step at a time.
A trace is a record of what a program does as it runs. For a loop, a trace shows the value of its variables, the result of each condition, and any output. Tracing is especially useful when a loop has more than one possible path.
Trace a loop one step at a time
An iteration is one run of a loop’s body. A condition is a true-or-false test that controls whether the loop repeats.
Consider this program:
public class TraceLoop {
public static void main(String[] args) {
int count = 0;
while (count < 3) {
System.out.println(count);
count++;
}
}
}The program prints 0, 1, and 2, each on a separate line. To see why, trace the value of count:
| `count` before the test | Is `count < 3` true? | Value printed | `count` after `count++` |
|---|---|---|---|
| 0 | Yes | 0 | 1 |
| 1 | Yes | 1 | 2 |
| 2 | Yes | 2 | 3 |
| 3 | No | None | No change |
The last row matters. When count is 3, the condition is false, so the body does not run again.
When you trace a loop:
- Write down the starting values.
- Test the condition at the correct point.
- If the body runs, follow its statements in order.
- Record any changed values and output.
- Repeat until the loop ends.
An increment is an increase in a value. Here, count++ adds 1 to count. The increment moves count toward a value that makes the condition false.
Check the boundary
A boundary is an edge of the values a loop should cover. For example, if you want to print the numbers from 0 through 2, the last value is a boundary.
Compare these conditions when the loop variable starts at 0 and increases by 1:
| Condition | Values included | Number of iterations |
|---|---|---|
| `count < 3` | 0, 1, 2 | 3 |
| `count <= 3` | 0, 1, 2, 3 | 4 |
| `count < 2` | 0, 1 | 2 |
The symbol < means “less than.” The symbol <= means “less than or equal to.” That small difference can add an extra iteration.
An off-by-one error happens when a loop runs one time too many or one time too few. To find one, ask:
- What is the first value the body uses?
- What is the last value the body should use?
- Is that last value allowed by the condition?
- What value makes the loop stop?
For example, to print 1 through 3, inclusive, start at 1 and use count <= 3. “Inclusive” means the named end value is included.
Check array boundaries
An array holds a fixed number of values. An index is a number that identifies a position in the array. Java array indexes start at 0.
This program visits every element in values:
public class ArrayBoundaries {
public static void main(String[] args) {
int[] values = {4, 7, 9};
for (int i = 0; i < values.length; i++) {
System.out.println("Index " + i + ": " + values[i]);
}
}
}The array’s length is 3, but its last index is 2.
| `i` | Is `i < values.length` true? | Element read |
|---|---|---|
| 0 | Yes | `values[0]`, which is 4 |
| 1 | Yes | `values[1]`, which is 7 |
| 2 | Yes | `values[2]`, which is 9 |
| 3 | No | None |
If the condition were i <= values.length, the body would also try to read values[3]. That index does not exist. Java would stop the program with an ArrayIndexOutOfBoundsException: an error caused by using an invalid array index.
Also consider an empty array. Its length is 0, so i < values.length is false at the first test. The loop correctly runs zero times. Reading values[0] without first checking for an element would cause an error.
Check that the loop can stop
Termination means that a loop finishes. A loop that keeps repeating without reaching an exit is called an infinite loop.
For a condition-controlled loop, find the value that will make the condition false. Then check that the loop moves toward that value on every path that needs to repeat.
In the first example:
- The loop continues while
count < 3. - The value
3makes that condition false. - Each iteration adds
1tocount. - Starting at
0, the loop reaches3and stops.
A common mistake is to forget the update. If count stays at 0, then count < 3 stays true. Another mistake is to update in the wrong direction: subtracting 1 from count does not move it toward 3.
A loop may also stop with break. In that case, check that the break can actually be reached when it is needed. A loop designed to repeat until break is not necessarily an error, but it needs a reliable way to exit.
Do not rely on an exact value that may be skipped
Suppose a counter starts at 0 and increases by 2 each time. It takes the values 0, 2, 4, 6, and so on. It skips 5.
A condition such as count != 5 means “continue while count is not equal to 5.” With that starting value and update, the counter never reaches 5, so that condition does not provide an exit. If the goal is to stop when the counter reaches or passes 5, count < 5 fits better: it becomes false when count reaches 6.
Also be careful with very large values. An int has a largest value, 2,147,483,647. Adding 1 to that value wraps it around to a negative value. This is called overflow. A loop that expects an int to grow beyond its largest value may not stop as expected.
Trace `continue` and updates together
The statement continue skips the rest of the current iteration. In a while loop, that means it can also skip an update placed later in the body.
This program updates i before it may use continue:
public class SkipOddNumbers {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
int current = i;
i++;
if (current % 2 != 0) {
continue;
}
System.out.println(current);
}
}
}The operator % gives the remainder after division. An odd number has a remainder of 1 when divided by 2. The program prints 0, 2, and 4.
| `current` | `i` after the increment | Is `current` odd? | What happens? |
|---|---|---|---|
| 0 | 1 | No | Print 0 |
| 1 | 2 | Yes | Skip the print |
| 2 | 3 | No | Print 2 |
| 3 | 4 | Yes | Skip the print |
| 4 | 5 | No | Print 4 |
After the last row, i < 5 is false. The loop stops.
If i++ were after the if statement, the loop would get stuck when i was 1. Each time, continue would skip the increment, leaving i at 1.
In a basic for loop, continue moves to the update in the loop header before the next condition test. Even so, trace that update: it still needs to move the loop toward an exit.
Check when the condition is tested
A while loop tests its condition before each iteration. A do-while loop tests after the body. That difference matters when the condition is false at the start.
public class TestTiming {
public static void main(String[] args) {
int count = 3;
while (count < 3) {
System.out.println("while: " + count);
count++;
}
count = 3;
do {
System.out.println("do-while: " + count);
count++;
} while (count < 3);
}
}The while body does not run, because 3 < 3 is false. The do-while body runs once before its test, so the program prints do-while: 3.
When tracing a do-while loop, do not test the condition before the first iteration. When checking a while or for loop, remember that the body may run zero times.
A loop variable’s scope is the part of the program where its name can be used. A variable declared in a for header, such as int i = 0, is available in that loop but not after it. If you need a result after the loop, store it in a variable declared before the loop.
Trace nested loops
A nested loop is a loop inside another loop. For each iteration of the outer loop, the inner loop can run through all its own iterations.
public class NestedTrace {
public static void main(String[] args) {
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 3; column++) {
if (column == 1) {
continue;
}
System.out.println(row + "," + column);
}
}
}
}Trace both variables. The inner loop starts with column at 0 each time the outer body runs.
| `row` | `column` | Action |
|---|---|---|
| 0 | 0 | Print `0,0` |
| 0 | 1 | Skip the print |
| 0 | 2 | Print `0,2` |
| 1 | 0 | Print `1,0` |
| 1 | 1 | Skip the print |
| 1 | 2 | Print `1,2` |
There are six inner iterations but only four printed lines. The continue affects the inner loop: it skips the rest of that inner iteration, not the rest of the outer loop.
A plain break inside the inner loop also affects only the inner loop. The outer loop can continue with its next iteration. When tracing nested loops, mark which loop each break or continue controls.
Check an early exit
A break can end a loop as soon as the program finds what it needs. This program searches an array for the first 7:
public class FindFirst {
public static void main(String[] args) {
int[] values = {4, 7, 9, 7};
boolean found = false;
for (int value : values) {
if (value == 7) {
found = true;
break;
}
}
System.out.println("Found: " + found);
}
}The enhanced for loop visits each array element in order. Its trace ends early:
| Value visited | Is it 7? | What happens? |
|---|---|---|
| 4 | No | Continue to the next element |
| 7 | Yes | Set `found` to `true` and break |
The program prints Found: true. It does not visit 9 or the second 7. If the array is empty, or has no 7, the loop ends without a break and found remains false.
Check whether an early exit matches the goal. It is useful for finding the first match. It would be wrong if the goal were to count every match.
Test the edges, not just the middle
A trace helps you reason about a loop. Running it with different inputs helps you check that reasoning. Choose small inputs so you can predict the result before running the program.
For a loop that visits an array, try these cases:
| Array | What to check |
|---|---|
| `{}` | The loop handles zero elements. |
| `{7}` | The only element is visited. |
| `{4, 7, 9}` | Elements in the middle are visited. |
| `{4, 9, 7}` | The last element is visited. |
| `{4, 9}` | A search handles no match. |
For a loop with a number as its limit, also try a starting value that makes the condition false immediately. For a do-while, check what happens in that same situation: its body still runs once.
If the result is wrong, compare the actual trace with your expected trace. Find the first row where they differ. Then check the condition, the update, and any break or continue reached on that row.
Exercises
Exercise
A loop starts with count = 1, runs while count <= 3, prints count, and then adds 1. What does it print, and what value stops it?
Show answer
It prints 1, 2, and 3. After the last increment, count is 4, so count <= 3 is false.
Exercise
An array has length 4. A loop starts at index 0 and uses the condition i <= values.length. What goes wrong?
Show answer
The loop tries to read index 4, but the valid indexes are 0 through 3. Use i < values.length to stop before index 4.
Exercise
In a while loop, i starts at 0. The loop runs while i < 3; its body uses continue when i == 1, and otherwise runs i++. Does the loop stop?
Show answer
No. The first iteration changes i to 1. After that, continue skips i++ every time, so i remains 1 and the condition stays true.
Exercise
An inner loop has 3 iterations for each of 2 outer iterations. It skips one print with continue during each set of inner iterations. How many lines does it print?
Show answer
It has 6 inner iterations and skips 2 prints, so it prints 4 lines.