From the free course AP Computer Science A on Lykke

2.11 Nested Iteration

Nested iteration places one loop inside another, allowing a program to repeat an entire sequence of actions for every pass of an outer loop. It is the natural tool for processing grids, tables, schedules, and every pair of items in a collection.

2.11 Nested Iteration

Nested iteration places one loop inside another, allowing a program to repeat an entire sequence of actions for every pass of an outer loop. It is the natural tool for processing grids, tables, schedules, and every pair of items in a collection.

The two-loop mental model

Imagine a hotel with several floors, each containing several rooms. The outer loop visits one floor at a time; the inner loop visits every room on the current floor. Only after the inner loop finishes does the outer loop move to the next floor.

for (int floor = 1; floor <= 3; floor++) {
    for (int room = 1; room <= 4; room++) {
        System.out.println("Floor " + floor + ", room " + room);
    }
}

The execution order is:

  1. floor becomes 1.
  2. The inner loop prints rooms 1 through 4.
  3. floor becomes 2.
  4. The inner loop starts over at room 1 and prints rooms 1 through 4.
  5. The same process occurs for floor 3.

The output contains $3 \times 4 = 12$ lines. The inner loop executes $4$ times for each of the $3$ outer-loop iterations.

A nested loop as a grid traversal

A two-dimensional array is organized by rows and columns. A standard traversal uses the outer loop for rows and the inner loop for columns:

int[][] temperatures = {
    {72, 75, 71},
    {68, 70, 69},
    {80, 78, 81}
};

for (int row = 0; row < temperatures.length; row++) {
    for (int col = 0; col < temperatures[row].length; col++) {
        System.out.print(temperatures[row][col] + " ");
    }
    System.out.println();
}

The outer loop selects a row. The inner loop uses temperatures[row].length, so it visits exactly the valid columns in that row. This matters because Java two-dimensional arrays may be ragged: different rows can have different lengths.

Worked example: finding the hottest reading

Suppose each row represents one day and each column represents a measurement taken that day. To find the largest reading, initialize a variable before either loop, then compare every element with it:

int[][] readings = {
    {14, 18, 13},
    {21, 19, 17},
    {16, 24, 20}
};

int maximum = readings[0][0];

for (int row = 0; row < readings.length; row++) {
    for (int col = 0; col < readings[row].length; col++) {
        if (readings[row][col] > maximum) {
            maximum = readings[row][col];
        }
    }
}

System.out.println(maximum);  // 24

Trace the key moment: when row is 2 and col is 1, the program examines 24, finds that it exceeds the current maximum, and updates maximum. Every other value is also examined, so no candidate is skipped.

Nested while loops

Nested iteration is not limited to for loops. The same structure can use while loops, but each loop needs its own initialization, condition, and update:

int row = 0;

while (row < readings.length) {
    int col = 0;

    while (col < readings[row].length) {
        System.out.print(readings[row][col] + " ");
        col++;
    }

    System.out.println();
    row++;
}

The inner variable col must be reset to 0 each time the outer loop advances to a new row. If it is initialized only once before the outer loop, the inner loop will work for the first row but may never run again.

Common misconception: “The inner loop runs only once”

Misconception: The inner loop runs once for the entire program. Correction: It runs once per outer-loop iteration. If the outer loop executes $r$ times and the inner loop executes $c$ times per outer iteration, the body executes $r \times c$ times.

Misconception: The inner loop must use a different kind of loop. Correction: Any valid combination works: for inside for, while inside for, or for inside while.

Misconception: array.length is always the number of columns. Correction: For a two-dimensional array, array.length gives the number of rows. array[row].length gives the number of columns in that particular row.

AP skill connection

Nested iteration especially develops Computational Thinking Practice 2: Develop Code, when you implement a systematic grid algorithm, and Computational Thinking Practice 3: Analyze Code, when you trace changing loop variables, count executions, test boundary conditions, and debug an incorrect traversal. It also supports Computational Thinking Practice 1: Design Code, because the row-column responsibility must be planned before implementation.

Retrieval check

For the following structure, how many times does System.out.println("*"); execute?

for (int a = 0; a < 4; a++) {
    for (int b = 1; b <= 3; b++) {
        System.out.println("*");
    }
}

The answer is $4 \times 3 = 12$. The outer loop selects four values of a; for each one, the inner loop prints three stars.

2.11 Nested Iteration - AP Computer Science A - image 1
2.11 Nested Iteration - AP Computer Science A - image 1
2.11 Nested Iteration - AP Computer Science A - diagram 1
2.11 Nested Iteration - AP Computer Science A - diagram 1

Source Materials

The whole course on Lykke · Browse all public course wikis