Lesson 2.11: Nested Iteration
Lesson 2.11: Nested Iteration
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.,
iandj) 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.
Practice Questions
System.out.println() called?for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
System.out.println(i + j);
}
}
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
// body
}
}
sum after this executes?int sum = 0;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
sum += i * j;
}
}
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i = j)
System.out.println(i + " " + j);
}
}
i != j not i = j
i = j is assignment, not comparison — compile error. Should be i != j to skip pairs where i equals j.for (int i = 2; i <= 4; i++) {
for (int j = 1; j < i; j++) {
System.out.print(j + " ");
}
}
1 1 2 1 2 3
1 2 1 2 3
1 1 2
1 2 3
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.for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(".");
}
System.out.println();
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// body
}
}
m + n
m * n
m * (m+1) / 2
n * (n+1) / 2
How many times does the loop body execute?
Mastery: Nested Iteration
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);
for (int i = 1; i <= 5; i++) {
for (int j = i + 1; j <= 5; j++) {
System.out.print("*");
}
}
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;
}
}
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]