Lesson 2.11: Nested Iteration

Unit 2 · Lesson 2.11 · Code Mechanics

Lesson 2.11: Nested Iteration

🕑 30–35 min · 8 Practice Questions · 4 Mastery Questions · Output Predictor + Count

What You'll Learn

  • 2.11.A: Develop nested iteration code and determine results. (EK 2.11.A.1)
  • Explain that the inner loop completes all iterations before the outer loop advances.
  • Calculate total inner body executions for nested loops with independent bounds.
  • Calculate total inner body executions when inner bound depends on outer variable.
  • Trace nested loop output step by step.

Key Vocabulary

Term Definition
nested iteration An iteration statement that appears inside the body of another iteration statement. The inner loop runs completely for each single iteration of the outer loop. (EK 2.11.A.1)
outer loop The enclosing iteration statement. Controls the number of 'passes' through the inner loop.
inner loop The iteration statement inside the outer loop body. Completes all its iterations before the outer loop advances to its next iteration. (EK 2.11.A.1)
total iterations The total number of times the inner loop body executes equals outer iterations × inner iterations per outer pass.
row-major order Processing a 2D structure by completing all columns of one row before moving to the next row. Typically produced by nesting a column loop inside a row loop.

How Nested Loops Execute (EK 2.11.A.1)

When one loop is nested inside another, the inner loop must complete all of its iterations before the outer loop can advance to its next iteration. This is the single most important rule for nested loops, and it is stated directly in the CED. Think of it like a clock: the inner loop is the seconds hand, the outer loop is the minutes hand — seconds complete a full revolution before minutes advance by one.

CED Connection (EK 2.11.A.1)

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

Structure

for (int outer = 0; outer < M; outer++) {
    // runs M times total

    for (int inner = 0; inner < N; inner++) {
        // runs N times per outer iteration
        // runs M * N times total
    }

    // outer body continues after inner loop completes
}

Worked Example — Full Trace (M=3, N=2)

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.print("(" + i + "," + j + ") ");
    }
    System.out.println();  // new line after each outer iteration
}

// Output:
// (1,1) (1,2)
// (2,1) (2,2)
// (3,1) (3,2)

// Total inner body executions: 3 * 2 = 6

Counting Total Executions

The total number of times the inner loop body executes is the product of the number of outer iterations and the number of inner iterations per outer pass. When the inner loop bound depends on the outer variable, you must sum, not multiply.

Worked Example — Independent Bounds (multiply)

// Outer runs 5 times, inner runs 4 times per outer iteration
// Total: 5 * 4 = 20 inner body executions
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 4; j++) {
        System.out.print("* ");
    }
}

Worked Example — Dependent Bounds (sum, not multiply)

// Inner bound depends on outer variable
// i=1: j runs 1 time | i=2: 2 times | i=3: 3 times | i=4: 4 times
// Total: 1+2+3+4 = 10 inner body executions
for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}
// Output:
// *
// * *
// * * *
// * * * *

Common Nested Loop Patterns

Worked Example — Multiplication Table

for (int row = 1; row <= 5; row++) {
    for (int col = 1; col <= 5; col++) {
        System.out.printf("%4d", row * col);
    }
    System.out.println();
}
// 1  2  3  4  5
// 2  4  6  8 10
// 3  6  9 12 15 ...

Worked Example — Count Matching Pairs

// Count pairs (i,j) where i < j and both divisible by 3
int count = 0;
for (int i = 1; i <= 20; i++) {
    for (int j = i + 1; j <= 20; j++) {   // j starts at i+1 to avoid duplicates
        if (i % 3 == 0 && j % 3 == 0) {
            count++;
        }
    }
}
System.out.println(count);  // 10

AP Trap: Inner Loop Resets Each Outer Iteration

The inner loop control variable is re-initialized every time the outer loop iterates. A common mistake is thinking the inner variable "remembers" where it left off. It always restarts from its initialization value at the beginning of each outer iteration.

AP Trap: Using the Same Variable in Both Loops

// WRONG: both loops use i — inner loop modifies outer's variable
for (int i = 0; i < 3; i++) {
    for (int i = 0; i < 3; i++) {  // compile error: i already declared
        System.out.print(i + " ");
    }
}
// Use different variable names: i for outer, j for inner

AP Trap: Total Execution Count on Exam

AP MCQ questions frequently ask "how many times does the statement execute?" Multiply outer × inner when bounds are independent. Sum when inner bound depends on outer. Always check whether the inner loop condition is < or <= before calculating.

Real-World Connection

Nested iteration is the engine behind 2D data processing. Image processing loops over every row and column of pixels. Matrix multiplication requires triple-nested loops. Generating all pairs of items for comparison (duplicate detection, closest-pair problems) uses nested loops. In Unit 4, you will use nested loops to traverse 2D arrays — the outer loop handles rows, the inner loop handles columns within each row.

Summary

  • Inner loop completes all iterations before outer loop advances. (EK 2.11.A.1)
  • Independent bounds: total = outer × inner iterations.
  • Dependent bounds: total = sum of inner iterations across each outer value.
  • Variable names: use distinct variables (e.g., i and j) for outer and inner loops.
  • Inner variable resets to its initialization value at the start of each outer iteration.
  • Preview: 2D array traversal in Unit 4 uses outer loop for rows, inner loop for columns.
Tier 2 · AP Practice

Practice Questions

MCQ 1
How many times is System.out.println() called?

for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.println(i + j);
    }
}
A 7
B 12
C 9
D 16
B. Outer runs 4 times, inner runs 3 times per outer iteration. 4 × 3 = 12 total calls.
MCQ 2
What is printed?

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}
A 3 rows of 3 stars each
B Row 1: 1 star, Row 2: 2 stars, Row 3: 3 stars
C Row 1: 3 stars, Row 2: 2 stars, Row 3: 1 star
D 9 stars in one row
B. Inner bound is i. When i=1: j runs once. When i=2: j runs twice. When i=3: j runs three times. Triangle pattern.
MCQ 3
How many total times does the inner loop body execute?

for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        // body
    }
}
A 10
B 15
C 25
D 5
B. Inner runs 1+2+3+4+5 = 15 times total (triangular sum formula: 5×6/2=15).
MCQ 4
What is the value of sum after this executes?

int sum = 0;
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        sum += i * j;
    }
}
A 36
B 9
C 18
D 27
A. i=1: 1+2+3=6. i=2: 2+4+6=12. i=3: 3+6+9=18. Total: 6+12+18=36.
MCQ 5
SPOT THE ERROR: A student wants to print all pairs (i,j) where i != j, both from 1 to 3.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i = j)
            System.out.println(i + " " + j);
    }
}
Predict the answer before reading the options.
A Should use i != j not i = j
B Outer loop bound should be 4
C Inner loop should start at i+1
D Both A and B are errors
A. i = j is assignment, not comparison — compile error. Should be i != j to skip pairs where i equals j.
MCQ 6
What is printed by this nested loop?

for (int i = 2; i <= 4; i++) {
    for (int j = 1; j < i; j++) {
        System.out.print(j + " ");
    }
}
Predict the answer before reading the options.
A 1 1 2 1 2 3
B 1 2 1 2 3
C 1 1 2
D 1 2 3
B. i=2: j runs 1 (j<2). i=3: j runs 1,2. i=4: j runs 1,2,3. Output: 1 1 2 1 2 3. Wait — that is A. Let me recheck: i=2: j=1 only (1<2). i=3: j=1,2 (1<3, 2<3). i=4: j=1,2,3. Output: 1 [space] 1 2 [space] 1 2 3. So 1 1 2 1 2 3 = A.
MCQ 7
How many times does the OUTER loop body execute (including the inner loop)?

for (int i = 0; i < 6; i++) {
    for (int j = 0; j < 6; j++) {
        System.out.print(".");
    }
    System.out.println();
}
A 6
B 12
C 36
D 6 (outer) with 36 dots total
A. The outer loop body (everything between outer { }) executes 6 times. The println runs 6 times. The dots print 36 times total. The question asks about outer loop body executions = 6.
MCQ 8
Which expression gives the total number of times the inner body executes?

for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
        // body
    }
}
Predict the answer before reading the options.
A m + n
B m * n
C m * (m+1) / 2
D n * (n+1) / 2
B. Outer runs m times, inner runs n times per outer iteration. Total = m × n. (EK 2.11.A.1)
PRACTICE WITH A GAME — CHOOSE ONE:
Output Predictor — Nested Loops
Trace the nested loop and type the exact output.
Question 1 of 3  ·  Score: 0

Done!
You got 0 of 3 correct.
Predict the Count — Nested Loops
Count how many times the inner body executes in total.
Question 1 of 3  ·  Score: 0

How many times does the loop body execute?

Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: Nested Iteration

MCQ 1
What is printed?

int total = 0;
for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= 4; j++) {
        if (i == j) total += i;
    }
}
System.out.println(total);
Predict the answer before reading the options.
A 10
B 16
C 4
D 36
A. Only adds when i==j: adds 1,2,3,4. Total=10.
MCQ 2
How many asterisks are printed?

for (int i = 1; i <= 5; i++) {
    for (int j = i + 1; j <= 5; j++) {
        System.out.print("*");
    }
}
A 10
B 15
C 20
D 5
A. i=1: j=2,3,4,5 (4). i=2: j=3,4,5 (3). i=3: j=4,5 (2). i=4: j=5 (1). i=5: j>5, 0. Total=4+3+2+1=10.
MCQ 3
If the outer loop runs M times and inner loop runs N times per outer iteration, the inner body executes:
A M + N times
B M × N times
C M² times
D N² times
B. (EK 2.11.A.1) When bounds are independent, total inner iterations = outer iterations × inner iterations per pass = M × N.
MCQ 4
What value is in result[2][2] after this?

int[][] result = new int[3][3];
for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 3; c++) {
        result[r][c] = r * 3 + c;
    }
}
Predict the answer before reading the options.
A 4
B 6
C 8
D 9
C. result[2][2] = 2*3+2 = 8.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]