AP® Computer Science A · Unit 2 · Topic 2.11

Nested Loops and How Often the Inside Runs

A nested loop is a loop inside another loop, and the inner loop runs completely, start to finish, every single time the outer loop takes one step. Total executions multiply instead of add.

Think of the outer loop as picking a row and the inner loop as filling in every column in that row. Each time the outer loop advances one step, the inner loop doesn't continue where it left off — it reinitializes completely, running from its own starting condition through to its own ending condition all over again. That's why the work multiplies rather than adds: an outer loop of m passes wrapping an inner loop of n passes gives m times n total executions of the inner body, not m plus n.

This matters because the inner loop's counter is a separate variable with its own scope, created fresh (or reset) each time control re-enters the inner loop's header. It has no memory of the value it held on the previous outer pass. Students tracing this by hand should build a trace table with one row per inner-loop execution, grouped by outer-loop pass, to see the reset happen concretely.

Nested loops connect directly to loop bounds that depend on an outer variable, which is where the simple multiplication rule breaks and becomes a sum instead. When the inner bound changes with each outer pass, like running i times during the i-th pass, you add up a changing number of iterations rather than multiplying by a constant. That sum is where nested loops meet the idea of accumulating totals across iterations, a skill that carries forward into analyzing how much total work any piece of repeated code does.

Key terms

nested loop
A loop written inside the body of another loop, so the inner loop runs fully on every pass of the outer one.
outer loop
The loop that controls how many times the entire inner loop restarts and runs.
inner loop
The loop nested inside another loop, reinitialized and run to completion each time the outer loop advances.
trace table
A table tracking variable values row by row as a program executes, often one row per loop pass.
triangular number
The sum 1+2+...+n, equal to n(n+1)/2, that arises when an inner loop's bound grows with the outer counter.

Watch it explained

  1. How it worksHow does the inner loop restart from the beginning on every pass of the outer one?
  2. Worked exampleFind how many times the body runs when an outer loop of 4 wraps an inner loop of 6.
  3. Worked exampleTrace an inner loop whose bound depends on the outer counter, for i running 1 to 4.
  4. Common mistakeWhy doesn't the inner counter keep its value from the previous outer pass?

Check yourself

Your turn1 of 2
An outer loop runs m times and an inner loop runs n times inside it, with one statement in the inner body. Write a closed-form expression, in terms of m and n, for how many times that statement executes.

End of topic.