Unit 2 · 18 min

2.11 Nested Iteration

In nested loops, the inner loop finishes a complete run for every single step of the outer loop.

Summary, objectives and course and exam description (CED) codes

Nested iteration means one loop is written inside the body of another loop. Each time the outer loop runs its body, the inner loop runs through every one of its iterations, and only then does the outer loop move on to its next iteration. If the outer loop runs m times and the inner loop runs n times each time, the inner body runs m times n times in total.

By the end of this session you can

  • 2.11.A Develop code to represent nested iterative processes and determine the result of these processes.

2.11.A2.11.A.1

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. A loop inside a loop

A nested iteration statement is a loop placed inside the body of another loop. The order is strict: once the inner loop starts, it finishes every one of its iterations, and only then can the outer loop go on to its next iteration 2.11.A.1.

for (int round = 1; round <= 2; round++) {
    for (int player = 1; player <= 3; player++) {
        System.out.println("Round " + round + ", player " + player);
    }
    System.out.println("End of round " + round);
}

Output:

Round 1, player 1
Round 1, player 2
Round 1, player 3
End of round 1
Round 2, player 1
Round 2, player 2
Round 2, player 3
End of round 2

The inner loop ran all 3 players before the outer loop moved from round 1 to round 2, and it started again at player 1 in round 2. The inner body ran 2 times 3 = 6 times.

2. Rows and columns

Think of the outer loop as rows and the inner loop as columns. print stays on the same line; println after the inner loop ends the row.

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

Output:

1 2 3 4 
2 4 6 8 
3 6 9 12 

Watch out: a per-row result must be reset inside the outer loop. This code totals each row of the table above:

for (int row = 1; row <= 3; row++) {
    int rowTotal = 0;
    for (int col = 1; col <= 4; col++) {
        rowTotal += row * col;
    }
    System.out.println("Row " + row + " total: " + rowTotal);
}

Output:

Row 1 total: 10
Row 2 total: 20
Row 3 total: 30

If int rowTotal = 0; were moved above the outer loop, the totals would pile up: 10, 30, 60.

3. Inner bounds that depend on the outer loop

When the inner loop’s Boolean expression uses the outer loop control variable, each row has a different length. A triangle:

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("*");
    }
    System.out.println();
}

Output:

*
**
***
****
i inner loop values of j stars printed
1 1 1
2 1, 2 2
3 1, 2, 3 3
4 1, 2, 3, 4 4

The inner body ran 1 + 2 + 3 + 4 = 10 times. Changing the inner loop to start at j = i and run while j <= 4 would print the rows in the other order: 4, 3, 2, 1 stars.

A number pattern built the same way:

for (int i = 1; i <= 3; i++) {
    for (int j = i; j <= 3; j++) {
        System.out.print(j);
    }
    System.out.println();
}

Output:

123
23
3

4. Checking pairs in a string

Nested loops can compare every character with every later character. Does a code contain any repeated letter? The inner loop starts at j = i + 1, so each pair is checked once and no letter is compared with itself.

String code = "PLANET";
boolean repeat = false;
for (int i = 0; i < code.length(); i++) {
    for (int j = i + 1; j < code.length(); j++) {
        if (code.substring(i, i + 1).equals(code.substring(j, j + 1))) {
            repeat = true;
        }
    }
}
System.out.println("Repeat: " + repeat);

Output:

Repeat: false

With "LETTER" instead, the code prints Repeat: true (E and T both repeat). For a 6-letter string the inner body runs 5 + 4 + 3 + 2 + 1 = 15 times.

A while loop can be nested in a for loop too. Count the digits of each number from 8 to 12:

for (int n = 8; n <= 12; n++) {
    int temp = n;
    int digits = 0;
    while (temp > 0) {
        digits++;
        temp /= 10;
    }
    System.out.print(digits + " ");
}
System.out.println();

Output:

1 1 2 2 2 

The copy temp matters: dividing n itself would change the outer loop control variable and break the outer loop.

5. Common nested loop errors

Using the same name for both loop control variables does not compile when both are declared in their headers:

for (int i = 0; i < 3; i++) {
    for (int i = 0; i < 2; i++) {
        System.out.print(i);
    }
}
error: variable i is already defined in method main(String[])

Using the outer variable in the inner header by mistake (j < i when you meant j < 3) changes how many times the inner body runs. The first row can even run zero times:

int count = 0;
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < i; j++) {
        count++;
    }
}
System.out.println(count);

Output:

3

With j < 3 the count would be 9. Here the inner loop runs 0, 1 and 2 times. To check nested loops, write a small table with one row per outer iteration and list what the inner loop does in that row.

Lock it in: memory hooks

  • ClockMinutes are the inner loop: they go all the way round before the hour moves once.
  • CountingRectangle: rows times columns. Triangle: 1 + 2 + ... + n.
  • Pairsj starts at i + 1: every pair once, never a letter with itself.

Common misconceptions

  • "The inner and outer loops take turns, one step each."

    Not quite. The inner loop runs all of its iterations for each single iteration of the outer loop. Only then does the outer loop move on.

  • "The inner loop's variable keeps its value between outer iterations."

    Not quite. When the inner loop control variable is declared in the inner header, it is created and initialized again every time the outer loop body runs.

  • "Total iterations of nested loops is outer + inner."

    Not quite. It is outer times inner when the inner count is fixed: 4 outer iterations with 5 inner iterations each run the inner body 20 times.

Exam traps

  • println inside the inner loop prints one item per line; println after the inner loop ends each row.
  • A row total declared before the outer loop keeps growing instead of starting again for each row.
  • Reusing i for both loops does not compile when both are declared in their headers.
  • When the inner loop starts at j = i, the rows get shorter; trace the first and last rows.

2PracticeRecall it, then check yourself

In 30 seconds

  1. A nested loop is a loop inside the body of another loop.
  2. For each iteration of the outer loop, the inner loop runs to completion.
  3. Fixed bounds: the inner body runs (outer iterations) times (inner iterations).
  4. When the inner bound depends on the outer variable, add up the inner counts row by row.
  5. Use different loop control variables (often i and j), and reset per-row accumulators inside the outer loop.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Nested Iteration

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following code segment. How many times is "*" printed? 2.11.A.1
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 3; j++) {
            System.out.print("*");
        }
    }
    Show answer

    Answer: C. For each of the 4 iterations of the outer loop, the inner loop completes all 3 of its iterations, so the body runs 4 times 3 = 12 times. 7 adds the loop counts instead of multiplying them, and 16 uses 4 for both loops.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 2.11.A.1
    for (int i = 3; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            System.out.print(j);
        }
        System.out.print(" ");
    }
    Show answer

    Answer: A. The outer loop sets i to 3, 2, 1. For each value, the inner loop prints j from 1 up to i, then a space: "123", "12", "1". "321 21 1" prints i instead of j, and "123 23 3" would need the outer loop to count up from 1 and the inner loop to start at i instead of 1.

  3. 3 Consider the following code segment. What is printed as a result of executing the code segment? 2.11.A.1
    int total = 0;
    for (int r = 1; r <= 3; r++) {
        for (int c = 1; c <= 2; c++) {
            total += r;
        }
        System.out.print(total + " ");
    }
    Show answer

    Answer: D. total is declared before the outer loop, so it is never reset. Each row adds r twice: after row 1 the total is 2, after row 2 it is 2 + 4 = 6, after row 3 it is 6 + 6 = 12. "2 4 6" is the per-row total, which would need int total = 0; inside the outer loop.

  4. 4 Consider the following code segment. What is printed as a result of executing the code segment? 2.11.A.1
    int count = 0;
    for (int i = 1; i <= 5; i++) {
        for (int j = i; j <= 5; j++) {
            count++;
        }
    }
    System.out.println(count);
    Show answer

    Answer: B. The inner loop starts at i, so it runs 5, 4, 3, 2 and 1 times as i goes from 1 to 5, a total of 15. 25 assumes the inner loop always runs 5 times. 10 would come from j < 5 or a similar off by one change.

  5. 5 A for loop is nested inside the body of another for loop. Which of the following best describes how the two loops execute? 2.11.A.1
    Show answer

    Answer: D. The inner loop is part of the outer loop's body, so each time the outer body runs, the inner loop starts again and runs to completion before the outer loop continues to its next iteration. The loops do not alternate single steps, and the inner loop runs once per outer iteration, not just once in total.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Inner body executions for common nested loop shapes (n outer iterations) three shapes CED 2.11.A.1
    1. rectangle, inner runs m timesn * m
    2. triangle, inner runs i times for i = 1 to nn(n + 1) / 2
    3. pairs, j from i + 1 to n - 1 for i = 0 to n - 1n(n - 1) / 2

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Nested iterationtap to flip

    A loop inside the body of another loop. The inner loop completes all its iterations before the outer loop continues to its next iteration.

    Example and CED codes
  • for looptap to flip

    An iterative statement whose header has three parts: the initialization (runs once), the Boolean expression (checked before each iteration) and the update (after each iteration).

    Example and CED codes
  • while looptap to flip

    An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.

    Example and CED codes
  • Loop control variabletap to flip

    The variable that controls how many times a loop runs. In a for loop it is the variable set up by the initialization in the header.

    Example and CED codes
  • String traversaltap to flip

    Visiting the characters or substrings of a string one position at a time with a loop, usually with substring(i, i + 1).

    Example and CED codes
  • Statement execution counttap to flip

    The number of times a statement is executed by a program, usually calculated informally by tracing and analyzing the loops.

    Example and CED codes

Questions students ask

How do nested loops work in Java?

The outer loop starts an iteration, then the inner loop runs all of its iterations. When the inner loop ends, the outer loop goes to its next iteration and the inner loop starts again from the beginning.

How many times does the inner loop run?

If the outer loop runs m times and the inner loop runs n times for each, the inner body runs m * n times. If the inner bound depends on the outer variable, add up the counts for each outer iteration.

How do I print a triangle of stars with nested loops?

Let the outer loop choose the row, and let the inner loop print as many stars as the row number, then call println after the inner loop to end the row.

Can I nest a while loop inside a for loop?

Yes. Any kind of loop can be nested inside any other kind.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure