AP Computer Science A · Unit 2: Selection & Iteration
2.11 Nested Iteration Statements
What is nested iteration?
A nested loop is a loop placed inside another loop. The outer loop controls how many times the inner loop runs completely. For each single pass of the outer loop, the inner loop executes all of its iterations before control returns to the outer loop for its next pass.
Counting total iterations
If the outer loop runs n times and the inner loop runs m times per outer pass, the inner statements execute n × m total times. This is essential for analyzing 2D array traversal (rows × columns) and patterns like printing grids or triangles.
Common uses & pitfalls
Nested loops are used to process 2D arrays, generate patterns, and compare pairs of elements. A common mistake is reusing the same loop variable name in both loops, or confusing rows and columns when indexing `array[row][col]`. Always trace small examples to verify logic.
Key terms
- Nested loop
- A loop placed inside another loop; the inner loop runs completely for each iteration of the outer loop.
- Total iterations formula
- If outer loop runs n times and inner loop runs m times per pass, total inner executions = n × m.
- Outer loop role in 2D array traversal
- Typically controls the row index while the inner loop controls the column index.
- Common nested loop bug
- Reusing the same loop variable name in both loops, or failing to reset the inner loop's control variable when needed.
- Example use case for nested iteration
- Printing patterns (e.g., triangles), processing 2D arrays, or comparing all pairs of elements in a collection.
Try an AP-style question
Code
int count = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
count++;What is count?
- 7
- 12
- 9
- 16
Show the answer
B. 3 × 4.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 2.11 free in APrep