Nested Iteration
| English | Chinese | Pinyin |
|---|---|---|
| nested iteration | 嵌套迭代 | qiàn tào dié dài |
A loop inside a loop
- Nested iteration 嵌套迭代 puts one loop inside another's body.
- The inner loop runs completely for each pass of the outer loop.
- Outer runs
mtimes, inner runsntimes each → the inner body runsm × ntimes. - Nesting handles grids, tables, and all-pairs comparisons.
Rows and columns
- A common use: outer loop for rows, inner loop for columns.
for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { ... } }- For each row, the inner loop sweeps all columns before the outer advances.
- This visits every cell of a 2-D grid in order.
Tracing the order
- The inner loop finishes all its passes, then the outer takes one step.
- Outer
r=0: innerc=0,1,2; outerr=1: innerc=0,1,2; and so on. - Reset any inner counter at the start of each outer pass.
- Trace slowly — mixing up which loop advances is a common mistake.
Watch the inner variable
- Declare the inner loop's counter inside or reset it each outer pass.
- If you reuse an outer variable in the inner condition, watch for interference.
- The inner and outer counters should be independent unless you intend otherwise.
- A triangle pattern (
cfrom0tor) makes the inner count depend on the outer.
In nested loops, the inner loop runs FULLY for every single outer pass. So the inner body executes outer × inner times — a 10 × 10 nest runs its inner body 100 times, not 20. Reset the inner counter at each outer pass (declaring it in the inner for header does this automatically), or the second outer pass starts where the first left off.
Printing a 3×3 grid of stars:
for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) { print("*"); } println(); }- Outer runs
3times; inner runs3each →9stars total. - Each outer pass prints one row of three, then a newline.
Nested iteration puts a loop inside another; the inner loop runs fully for each outer pass, so the inner body executes outer × inner times. It's the pattern for grids (outer = rows, inner = columns). Reset the inner counter each outer pass, and trace carefully — the inner finishes before the outer advances.
Nested loops sweep a grid
Outer = rows, inner = columns; the inner loop fills each row.
Outer loop runs 3 times, inner runs 3 times each. How many times does the inner body run?
3 × 3 = 9.
In nested loops, the inner loop runs fully for every single pass of the outer loop.
That's why the inner body runs outer × inner times.
For a 2-D grid, which loop typically handles the columns?
Outer = rows, inner = columns.
A 10 × 10 nested loop runs its inner body how many times?
10 × 10 = 100.
Declaring the inner counter in the inner for-header resets it each outer pass.
A fresh int i in the inner header restarts it each time.