---
title: "Nested Iteration Processes | FiveStudy"
description: "Loops inside loops multiply. The full grid visits every pair; j = i + 1 keeps each unordered pair once."
url: https://fivestudy.com/guides/nested-iteration-processes
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Nested Iteration Processes

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Selection and Iteration

AP® Computer Science A · Selection and Iteration

# Nested *Iteration*

Loops inside loops: the order in which their bodies run, inner bounds that depend on the outer variable, counting how many times the inner body executes, and using nested loops to build patterns and examine every pair.

1. Loops Inside Loops 2. Order of Execution 3. Dependent Bounds 4. Counting Executions 5. Examining Pairs 6. Resetting the Inner Loop

Big Picture

**Nested iteration statements** are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration. Nested loops handle two-dimensional work: rows and columns of a table, lines of a pattern, or every pair of values from a range. The key skills are following the order of execution and counting how many times the innermost statements run.

## 1 Loops Inside Loops

A loop body can contain any statements, including another loop. The loop that contains the other is the **outer loop**; the one inside is the **inner loop**. Each time the outer loop's body runs, the inner loop runs from start to finish. Nested loops are the natural tool whenever a task has two dimensions, such as rows and columns, or whenever every combination of two values must be considered.

Each loop needs its own control variable, conventionally `i` for the outer loop and `j` for the inner one, or descriptive names such as `row` and `col`. The inner loop can use the outer variable, but the outer loop should not depend on anything the inner loop leaves behind except through clearly named variables.

| Question | How to answer it |
| --- | --- |
| Which loop finishes first? | The inner loop completes all its iterations before the outer loop continues |
| How many times does the inner body run (fixed bound)? | Outer passes × inner passes |
| How many times (bound depends on outer variable)? | Add the inner pass counts for each outer value |
| Does the inner loop restart? | Yes, from its initialization, on every outer pass |

Worked Example 1 Rows and columns

### A Multiplication Table

Print a table with 3 rows and 4 columns, where each entry is row × column.

Code

```
for (int i = 1; i <= 3; i++)
{
    String row = "" + i;
    for (int j = 2; j <= 4; j++)
    {
        row = row + " " + (i * j);
    }
    System.out.println(row);
}
```

Output

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

1. 1 **Outer loop: one row per pass.** It starts a fresh `row` string with the first entry, `i × 1`.
2. 2 **Inner loop: the rest of the row.** For `j` from 2 to 4 it appends `i × j`.
3. 3 **Only after the inner loop finishes** is the row printed and the outer loop moves on.

**Result:** The output is three rows: 1 2 3 4, 2 4 6 8, 3 6 9 12. The outer loop controls rows and the inner loop controls the entries within each row.

Common Mistake 1 · Using the Same Variable for Both Loops

If the inner loop reuses the outer loop's variable, each changes the other and the loops behave unpredictably; with `for` loops that declare `int i` twice, the code does not compile. Give each loop its own control variable.

## 2 Order of Execution

When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration. With an outer loop over `i` = 1 to 3 and an inner loop over `j` = 1 to 4, the inner body runs for `j` = 1, 2, 3, 4 with `i` = 1, then all four again with `i` = 2, then with `i` = 3: twelve runs in total, row by row.

An odometer is a good picture: the right-hand digit (the inner loop) cycles through all its values before the next digit to the left (the outer loop) advances by one. Statements in the outer body that come after the inner loop run once per outer pass, after the inner loop has finished; statements before it run once per outer pass before the inner loop starts.

**Figure 1.** When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration.

| Outer i | Inner j values | Inner passes | Output for this i |
| --- | --- | --- | --- |
| 1 | 1, 2, 3 | 3 | i=1 j=1 / j=2 / j=3, end of i=1 |
| 2 | 1, 2, 3 | 3 | i=2 j=1 / j=2 / j=3, end of i=2 |

Worked Example 2 Order of execution

### Watching Both Variables

Predict the exact order of the output.

Code

```
for (int i = 1; i <= 2; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        System.out.println("i=" + i + " j=" + j);
    }
    System.out.println("end of i=" + i);
}
```

Output

```
i=1 j=1
i=1 j=2
i=1 j=3
end of i=1
i=2 j=1
i=2 j=2
i=2 j=3
end of i=2
```

1. 1 **`i` = 1.** The inner loop runs all three values of `j` before anything else happens.
2. 2 **After the inner loop** the outer body continues with its own statement: "end of i=1".
3. 3 **`i` = 2.** The inner loop starts over at `j` = 1, because its initialization runs again.

**Result:** Eight lines print, in the order shown. The inner loop restarts from its initialization on every outer pass and must finish before the outer loop advances.

## 3 Inner Bounds That Depend on the Outer Variable

The inner loop's header may use the outer loop variable. In a triangle pattern, row `r` has `r` stars, so the inner loop runs while `j <= r`: once on the first row, twice on the second, and so on. The inner loop can also start at the outer value, as in `for (int b = a; ...)`, which is how nested loops avoid examining the same pair twice.

Variables that must start fresh for each outer pass, such as a string being built for one row, are initialized inside the outer loop but before the inner loop. Variables that accumulate across the whole nested process, such as a total count, are initialized before the outer loop.

**Figure 2.** When the inner loop's bound uses the outer loop variable, each outer pass runs the inner loop a different number of times.

Worked Example 3 Dependent bounds

### A Triangle of Stars

Print 4 rows where row `r` has `r` stars.

Code

```
for (int r = 1; r <= 4; r++)
{
    String line = "";
    for (int j = 1; j <= r; j++)
    {
        line = line + "*";
    }
    System.out.println(line);
}
```

Output

```
*
**
***
****
```

1. 1 **The inner bound is `r`**, the outer variable, so the inner loop runs once on the first row, twice on the second, and so on.
2. 2 **`line` is reset** at the start of each outer pass, so each row starts empty.

**Result:** The output is a triangle: *, **, ***, ****. An inner bound that depends on the outer variable produces patterns whose rows differ in length.

Common Mistake 2 · Initializing a Row Variable in the Wrong Place

If the string for one row is created before the outer loop, rows pile onto each other; if it is created inside the inner loop, each row holds only one character. Create per-row variables inside the outer loop, before the inner loop begins.

## 4 Counting Inner-Body Executions

How many times a statement in the inner body runs is a frequent question, and a preview of analyzing how much work a program does. When the inner loop's count does not depend on the outer variable, multiply: 5 outer passes with 3 inner passes each gives 15 runs. When it does depend on the outer variable, add the inner counts for each outer pass: inner counts of 0, 1, 2, 3, 4 add to 10.

For the common pattern where the inner loop runs `i` times for `i` = 1 to `n`, the total is 1 + 2 + … + `n` = `n(n + 1) / 2`. Listing the inner count for the first few and last outer values, then adding, is a reliable method even when no formula comes to mind.

**Figure 3.** With a fixed inner bound, the inner body runs (outer passes) × (inner passes) times. With a bound that depends on the outer variable, add the inner counts for each outer pass.

| Inner loop header | Outer i from 0 to 4 | Total inner passes |
| --- | --- | --- |
| `for (int j = 0; j < 3; j++)` | 3 each time | 15 |
| `for (int j = 0; j < i; j++)` | 0, 1, 2, 3, 4 | 10 |
| `for (int j = 0; j <= i; j++)` | 1, 2, 3, 4, 5 | 15 |
| `for (int j = i; j < 5; j++)` | 5, 4, 3, 2, 1 | 15 |

Worked Example 4 Counting executions

### How Many Times Does the Inner Body Run?

Predict both counts.

Code

```
int a = 0;
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 3; j++)
    {
        a++;
    }
}
int b = 0;
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < i; j++)
    {
        b++;
    }
}
System.out.println(a + " " + b);
```

Output

```
15 10
```

1. 1 **Fixed bound.** 5 outer passes × 3 inner passes = 15.
2. 2 **Dependent bound.** For `i` = 0, 1, 2, 3, 4 the inner loop runs 0, 1, 2, 3, 4 times: 10 in total.

**Result:** The output is 15 10. Multiply when the inner count is fixed; add the counts for each outer pass when it changes.

## 5 Examining Every Pair

Nested loops can check every combination of two values: the outer loop chooses the first, the inner loop chooses the second, and an `if` inside tests the pair. If order matters, both loops run over the full range; if it does not, starting the inner loop at the outer value (or one past it) checks each unordered pair once and skips duplicates.

The same idea applies to strings: an outer loop over each position and an inner loop over every later position compare every pair of characters. This is how a program can count repeated letters or find whether any two positions hold the same character.

**Figure 4.** Nested loops can examine every pair of values. Starting the inner loop at the outer value checks each unordered pair exactly once.

Worked Example 5 Pairs

### Finding All Pairs With a Given Sum

List every pair of whole numbers a ≤ b, each from 1 to 9, whose sum is 10.

Code

```
int pairs = 0;
for (int a = 1; a <= 9; a++)
{
    for (int b = a; b <= 9; b++)
    {
        if (a + b == 10)
        {
            System.out.println(a + " + " + b);
            pairs++;
        }
    }
}
System.out.println(pairs + " pairs");
```

Output

```
1 + 9
2 + 8
3 + 7
4 + 6
5 + 5
5 pairs
```

1. 1 **Every pair once.** Starting the inner loop at `a` avoids listing both 1 + 9 and 9 + 1.
2. 2 **Selection inside.** Only pairs that meet the criterion print and are counted.

**Result:** Five pairs print, from 1 + 9 to 5 + 5. Nested loops examine combinations; the inner loop's starting value controls whether order matters.

Worked Example 6 Nested loops with strings

### Counting Matching Letter Pairs

Count the pairs of positions i < j in "banana" that hold the same letter.

Code

```
String word = "banana";
int matches = 0;
for (int i = 0; i < word.length(); i++)
{
    for (int j = i + 1; j < word.length(); j++)
    {
        if (word.substring(i, i + 1).equals(word.substring(j, j + 1)))
        {
            matches++;
        }
    }
}
System.out.println(matches);
```

Output

```
4
```

1. 1 **Pairs with i < j.** The inner loop starts at `i + 1`, so each pair of positions is compared once.
2. 2 **The a's** at 1, 3, 5 form 3 pairs; **the n's** at 2, 4 form 1 pair; "b" has no partner.

**Result:** The output is 4. Nested loops over the same string compare every character with every later character.

Common Mistake 3 · Counting Each Pair Twice

If both loops run over the full range, the pair (1, 9) is found once as a = 1, b = 9 and again as a = 9, b = 1, and a value can even be paired with itself. When order does not matter, start the inner loop at `a` (or `a + 1` to exclude self-pairs).

## 6 Resetting the Inner Loop

A `for` loop's initialization runs every time the loop statement is reached, so an inner `for` loop automatically restarts on each outer pass. An inner `while` loop does not have that built in: if its counter is declared and set before the outer loop, it keeps its final value after the first outer pass, and the inner loop runs zero times on every later pass.

Whenever an inner `while` loop is used, set its counter inside the outer loop, immediately before the inner loop. Tracing the second outer pass is the quickest way to catch this mistake, because the first pass always looks correct.

Worked Example 7 A common bug

### Forgetting to Reset the Inner Loop

The inner `while` loop's counter is declared outside the outer loop. Predict the output.

Code

```
int j = 1;
for (int i = 1; i <= 3; i++)
{
    while (j <= 2)
    {
        System.out.println(i + "," + j);
        j++;
    }
}
```

Output

```
1,1
1,2
```

1. 1 **First outer pass.** The inner loop prints 1,1 and 1,2, leaving `j` at 3.
2. 2 **Later passes.** `j` is still 3, so `j <= 2` is `false` immediately and the inner loop runs zero times.
3. 3 **Fix.** Set `j = 1;` at the start of each outer pass, or use a `for` loop, whose initialization runs every time it is reached.

**Result:** Only 1,1 and 1,2 print. An inner loop must start fresh on each outer pass; a `for` loop's header guarantees this, while a `while` loop needs an explicit reset.

Common Mistake 4 · Trusting the First Outer Pass

Nested loop bugs often appear only on the second or later outer pass: a counter that was not reset, an accumulator that was not cleared, or a bound that depends on the wrong variable. Always trace at least two outer passes.

### Four Habits for Nested Loops

#### 1. Inner Finishes First

All inner passes run before the outer variable changes.

#### 2. Multiply or Add

Fixed inner bound: multiply. Dependent bound: add.

#### 3. Place Each Variable Carefully

Totals before the outer loop; per-row values inside it.

#### 4. Trace Two Outer Passes

Resets and bounds fail on the second pass.

Core Synthesis

Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration. The number of times the inner body runs is the product of the pass counts when the inner bound is fixed, or the sum of the inner counts when the inner bound depends on the outer loop variable.

FiveStudy AP® Computer Science A Study Guide · Selection and Iteration · Nested Iteration Back to top ↑
