# AP® Computer Science A 2.11 Nested Iteration

Source: https://lockincs.com/ap-csa/unit-2/2-11-nested-iteration/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 2.11.A, 2.11.A.1

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.

## What you will learn

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

## 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.

## Common mix-ups

- Not true: The inner and outer loops take turns, one step each. The inner loop runs all of its iterations for each single iteration of the outer loop. Only then does the outer loop move on.
- Not true: The inner loop's variable keeps its value between outer iterations. 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.
- Not true: Total iterations of nested loops is outer + inner. 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.

## In 30 seconds

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

## Checkpoint: 5 practice questions

### Question 1

Consider the following code segment. How many times is `"*"` printed?

```java
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.print("*");
    }
}
```

- A. 7
- B. 9
- C. 12
- D. 16

**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.

### Question 2

Consider the following code segment. What is printed as a result of executing the code segment?

```java
for (int i = 3; i >= 1; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print(j);
    }
    System.out.print(" ");
}
```

- A. 123 12 1
- B. 321 21 1
- C. 1 12 123
- D. 123 23 3

**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.

### Question 3

Consider the following code segment. What is printed as a result of executing the code segment?

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

- A. 2 4 6
- B. 1 2 3
- C. 4 8 12
- D. 2 6 12

**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.

### Question 4

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int count = 0;
for (int i = 1; i <= 5; i++) {
    for (int j = i; j <= 5; j++) {
        count++;
    }
}
System.out.println(count);
```

- A. 25
- B. 15
- C. 10
- D. 5

**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.

### Question 5

A `for` loop is nested inside the body of another `for` loop. Which of the following best describes how the two loops execute?

- A. The loops take turns: one outer iteration, then one inner iteration, then one outer iteration, and so on.
- B. The inner loop completes all of its iterations once, and then the outer loop runs.
- C. The outer loop completes all of its iterations before the inner loop starts.
- D. For each iteration of the outer loop, the inner loop completes all of its iterations.

**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.

## 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.

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
