Skip to main content

Unit 2 · Topic 2.11

2.11 Nested Iteration

A nested loop is a loop inside another loop. It's how you print patterns, work through rows and columns, and compare every pair of items. The key rule is that the inner loop finishes all of its passes before the outer loop moves on.

Key terms

  • nested loop
  • inner loop
  • outer loop

How nested loops run

When a loop sits in the body of another loop, the outer loop starts its first pass, and then the inner loop runs completely, from its initialization until its condition is false. Only then does the outer loop do its update and start its next pass, which runs the inner loop completely again.

for (int r = 0; r < 2; r++) { for (int c = 0; c < 3; c++) { System.out.print(r + "" + c + " "); } System.out.println(); }

This prints 00 01 02 on the first line and 10 11 12 on the second. For r = 0, c goes 0, 1, 2. Then r becomes 1 and c starts over at 0. Think of a clock: the minute hand (inner loop) goes all the way around for each step of the hour hand (outer loop).

The r + "" + c trick joins the two numbers as text. Without the empty string, r + c would add them.

Inner loops that depend on the outer variable

The inner loop's bounds can use the outer loop's variable. Then the inner loop runs a different number of times on each outer pass. That's how you make triangle patterns:

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

On row 1 the inner loop prints one star, on row 2 two stars, and so on. The println after the inner loop ends each line.

Every pair

To compare every pair of items exactly once, start the inner loop one past the outer variable: for (int b = a + 1; ...). That skips comparing an item with itself and avoids counting the pair (2, 5) again as (5, 2). This pattern appears again in 4.5 for finding duplicates.

Tracing tips

Trace nested loops one outer pass at a time, and don't try to hold the whole thing in your head. Write down the outer variable's value, then list everything the inner loop does for that value. Pay attention to where each print statement sits: inside the inner loop, it runs once per inner pass; between the two loops, once per outer pass.

Worked examples

Try each one yourself first, then open the solution.

  1. Example 1

    Tracing a pattern

    What does this code print?for (int i = 3; i > 0; i--) { for (int j = 0; j < i; j++) { System.out.print(i); } System.out.print(" "); } System.out.println();

    Show the solution
    1. Step 1: Outer pass with i = 3: the inner loop runs for j = 0, 1, 2 and prints 3 each time, so 333. Then a space.
    2. Step 2: Outer pass with i = 2: j = 0, 1, so 22, then a space.
    3. Step 3: Outer pass with i = 1: j = 0 only, so 1, then a space.
    4. Step 4: i becomes 0, 0 > 0 is false, and the outer loop ends. The final println ends the line.

    Answer: It prints 333 22 1 (with a space at the end).

  2. Example 2

    Counting pairs

    This code looks at every pair of different numbers from 1 to 5. What does it print?int count = 0; for (int a = 1; a <= 5; a++) { for (int b = a + 1; b <= 5; b++) { if ((a + b) % 2 == 0) { count++; } } } System.out.println(count);

    Show the solution
    1. Step 1: Because b starts at a + 1, each pair appears once with a < b. There are 4 + 3 + 2 + 1 = 10 pairs in all.
    2. Step 2: A sum is even when both numbers are odd or both are even.
    3. Step 3: Odd numbers: 1, 3, 5 give the pairs (1, 3), (1, 5) and (3, 5). Even numbers: 2, 4 give (2, 4).
    4. Step 4: That's 4 pairs with an even sum.

    Answer: It prints 4.

Common mistakes

  • Thinking the two loops take turns. The inner loop finishes all its passes for each single outer pass.
  • Forgetting that the inner loop's variable resets every time the inner loop starts again.
  • Putting the println inside the inner loop when it belongs after it, which breaks every line apart.

On the exam

  • Questions often ask what pattern is printed or how many times a statement runs. Trace the first two outer passes carefully, find the pattern, then extend it.
  • Nested loops are the core of the 2D array free-response question (4.12 and 4.13).

Connected topics

Videos

Check yourself

4 questions on 2.11 Nested Iteration. Pick an answer to see if you got it, and why.

Question 1 of 4

Consider the following code segment.for (int i = 1; i <= 3; i++) { for (int j = i; j <= 3; j++) { System.out.print("*"); } System.out.println(); }What is printed as a result of executing the code segment?

Question 2 of 4

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

Question 3 of 4

Consider the following code segment.int count = 0; for (int i = 1; i <= 9; i++) { for (int j = i + 1; j <= 9; j++) { if (i + j == 10) { count++; } } } System.out.println(count);What is printed as a result of executing the code segment?

Question 4 of 4

Consider the following code segment.String s = ""; for (int a = 0; a < 2; a++) { for (int b = 0; b < 3; b++) { s += a + "" + b + " "; } } System.out.println(s);What is printed as a result of executing the code segment?

0 of 4 answered