Topic 2.11 — Nested Iteration
Goal: trace and write nested loops (a loop inside another loop), and recognize how the number of iterations grows when loops are nested.
The big idea
Nested iteration means you have a loop inside another loop. For each iteration of the outer loop, the inner loop runs completely.
Think: “For each row, do all the columns.”
Structure
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
// runs rows * cols times total
}
}
Total executions of the inner body ≈ (outer iterations) × (inner iterations).
Example: print a grid pattern
(Even if you don’t “print” on your site, this pattern is common for 2D work later.)
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
// do something for (r, c)
}
}
- Outer loop runs 3 times.
- Inner loop runs 4 times each outer iteration.
- Total inner body runs 12 times.
Nested loops for “all pairs”
Another common use: compare every item with every other item.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// work with pair (i, j)
}
}
Starting j at i + 1 avoids duplicate pairs and avoids comparing an element with itself.
Tracing nested loops (how to do it)
- Pick one outer-loop value.
- Run the inner loop fully (all inner values).
- Then move to the next outer-loop value and repeat.
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
// body
}
}
// i=1 with j=1,2,3 then i=2 with j=1,2,3
Common mistakes
- Forgetting which loop variable belongs to which loop.
- Updating the wrong variable inside the inner loop.
- Miscounting total iterations (forgetting it’s multiplication).
// Bug: accidentally increments i inside inner loop
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
i++; // ❌
}
}
Exam mindset
- Multiply iterations: outer × inner for total body runs.
- Trace by fixing the outer index and “sweeping” the inner index.
- Look for bounds like
j = i + 1that reduce work and avoid duplicates. - Be careful with off-by-one errors in both loops.
Quick self-check
- How many times does the inner body run: outer 4 times, inner 6 times?
- In a nested loop, which loop finishes first?
- What does starting
jati+1accomplish? - Trace:
for(i=0;i<2;i++) for(j=0;j<2;j++)— list (i,j) pairs. - What’s the most common tracing mistake with nested loops?