Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

AP Computer Science A: Deep Dive and FRQ Mastery — Alpha School

Lesson 8: Nested Loops, Loop Invariants and Debugging

Loops can be nested inside one another, and nested loops are the natural way to work with two-dimensional patterns: rows and columns, pairs of items, or a grid of values. The outer loop runs once, and for each of its iterations the inner loop runs to completion, so the total number of inner iterations is the product of the two counts. A pair of loops from 1 to 3, for example, runs the inner body nine times. When you trace nested loops, track the outer variable in one column and the inner variable in another, and write down what happens for one full outer iteration before moving on.

A loop invariant is a statement that is true before each iteration of a loop, and it is the key to reasoning about whether a loop is correct. For a loop that sums an array, the invariant might be that the running total equals the sum of the elements processed so far; for a loop that searches for a value, it might be that the value has not been found among the elements checked so far. If the invariant is true at the start, stays true after each iteration, and implies the desired result when the loop ends, then the loop is correct. You do not need to write formal proofs on the exam, but thinking in terms of invariants helps you design loops that work the first time.

Debugging loops means finding the difference between what the loop does and what you intended, and the most effective technique is the simplest: trace with small inputs. Run the loop by hand for two or three iterations, writing down the variables, and compare with what you expected. If the loop runs forever, check the update and the condition; if it runs the wrong number of times, check the boundaries; if it produces the wrong values, check the body. Adding a temporary print statement inside the loop to show the variables at each iteration is a legitimate debugging technique, and it is often faster than staring at the code.

Nested loops also appear in algorithms you will meet again: comparing every pair of items, filling a two-dimensional array, or drawing a pattern of stars. In each case, ask what the outer loop controls and what the inner loop controls, and whether the inner loop's bounds depend on the outer variable. A triangular pattern, for example, has an inner loop that runs up to the outer variable, not to a fixed limit, and that dependence is the whole point of the pattern. In free-response answers, a trace table with columns for each loop variable is the clearest way to show nested-loop behaviour.

A trace table is the most reliable way to follow nested loops, and it is worth building one even for short examples. Make a column for each loop variable and one for each value the body changes, then add a row for each pass through the inner body. The table shows at a glance how many times the inner loop ran, which values the outer variable had at each stage, and where the result first went wrong if it did. For exam questions, a short trace table is also an excellent way to present your answer: it shows the marker exactly how you reached your result, and it earns credit for the reasoning even if the final number has a slip.

A worked example

Worked example: the nested loops below print a right triangle of stars. For each row, the inner loop prints as many stars as the row number, and the outer loop moves to the next row. Trace it for rows 1 to 3 and the pattern is clear.

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= row; col++)
    {
        System.out.print("*");
    }
    System.out.println();
}
// output:
// *
// **
// ***

When row is 1, the inner loop runs once and prints one star; when row is 2, it runs twice; when row is 3, three times. The inner bound col <= row depends on the outer variable, which is what makes the triangle grow. The invariant of the outer loop is that rows 1 to row − 1 have been printed correctly, and when the loop ends, all three rows are done. If the inner bound were col <= 3 instead, every row would print three stars and the pattern would be a rectangle, not a triangle.

Key Terms

Nested loop
A loop inside the body of another loop; the inner loop runs fully for each outer iteration.
Loop invariant
A statement true before each iteration of a loop, used to reason about correctness.
Trace table
A table recording variable values at each step of a program's execution.
Debugging
Finding and fixing the difference between what code does and what was intended.

Discussion Questions

  1. If an outer loop runs 4 times and an inner loop runs 5 times per outer iteration, how many times does the inner body run?
  2. What is a loop invariant, and how does it help you trust a loop?
  3. Why is tracing with small inputs the best first step in debugging a loop?

Practice Questions

  1. How many times does the body run in for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { } }?
  2. A loop sums numbers 1 to n. State a loop invariant for it.
  3. What pattern does the inner bound col <= row produce, and why?
  4. A loop that should run 10 times runs 11 times. What kind of error is this?
  5. Why might you put a print statement inside a loop while debugging?
Show answers
  1. 12 times, 3 × 4.
  2. After k iterations, the running total equals the sum of the numbers 1 to k.
  3. A triangle, because each row prints one more star than the row before.
  4. An off-by-one error, probably from using <= where < was needed, or starting at 0 instead of 1.
  5. To see the variable values at each iteration and find where they first differ from what you expected.
Keep reading to complete this lesson