Loops inside loops: multi-level iteration.
When a single sweep is not enough, nesting loops gives you the power to compare pairs, traverse grids, and build patterns.
A nested loop is a loop placed inside the body of another loop. For each iteration of the outer loop, the entire inner loop runs from start to finish.
Nested loops are essential for any task that involves pairs of elements — comparing items in an array, printing rectangular patterns, or traversing a 2D array row by row and column by column.
On the AP exam, nested loops show up in tracing problems, output-pattern questions, and almost every 2D-array FRQ.
Inner runs fully for every outer step.
Multiplication, not addition, governs total iterations.
Basic structure
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// executed rows * cols times
}
}
If the outer loop runs rows times and the inner loop runs cols times, the inner body runs rows * cols times in total.
Tracing tip
Always describe nested loops with the phrase: "for every outer iteration, the inner loop runs from start to finish." This mental model prevents most tracing errors.
Pattern example
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
This prints:
*
**
***
Notice how the inner loop's bound depends on the outer loop variable i — a powerful pattern used in many AP problems.
2D array traversal
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
System.out.print(grid[r][c] + " ");
}
System.out.println();
}
This is the standard row-major traversal pattern: the outer loop walks rows, the inner loop walks columns.
Vocabulary you must recognize in nested-loop questions.
AP CSA uses these terms throughout 2D-array problems.
- Outer loop — the enclosing loop; controls how many full inner sweeps happen.
- Inner loop — the loop placed inside the body of another; runs fully each time the outer iterates.
- Row-major traversal — visiting every column in a row before moving to the next row.
- Column-major traversal — visiting every row in a column before moving to the next column.
- Total iterations — usually the product of the loop bounds.
- Triangular pattern — when the inner loop's bound depends on the outer loop variable.
How nested loops are tested.
Patterns, totals, and 2D-array traversal dominate.
MCQ patterns to expect:
- What is printed? Trace by listing each (i, j) pair on paper.
- How many times does the inner statement execute? Multiply when bounds are independent; sum a series like
1 + 2 + 3 + ...when the inner bound depends on the outer. - Row-major vs column-major traversal questions appear in 2D array MCQs.
FRQ tip: 2D array FRQs almost always require nested for loops with arr.length and arr[r].length. Use these bounds — graders look for them by name.
Trace and count a triangular pattern.
When the inner bound depends on the outer, totals form a series.
Problem. How many times does the inner statement execute?
int count = 0;
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
count++;
}
}
System.out.println(count);
Step 1. Trace the inner loop bound for each outer iteration:
- i = 1 → inner runs 1 time → count = 1
- i = 2 → inner runs 2 times → count = 3
- i = 3 → inner runs 3 times → count = 6
- i = 4 → inner runs 4 times → count = 10
Step 2. Total: 1 + 2 + 3 + 4 = 10.
Answer. The program prints 10.
Why this matters. Because the inner bound depends on i, you cannot simply multiply. Always check whether the bounds are independent before using the multiplication shortcut.
Errors that derail nested loops.
Most issues come from variable confusion and wrong bounds.
- Reusing the same loop variable for both loops. Always use distinct variables like
iandj, orrandc. - Forgetting
println()after the inner loop when printing 2D patterns — every row collapses onto one line. - Swapping row and column indices. In Java,
grid[r][c]means rowr, columnc. Mixing this order causes wrong outputs or exceptions. - Using
grid.lengthfor both bounds. The inner bound must begrid[r].lengthbecause rows can vary in length in jagged arrays. - Multiplying when bounds depend on each other. If the inner bound depends on the outer variable, count by addition, not multiplication.
Nested-loop patterns at a glance.
The key structures you must read and write fluently.
Nested Loop Reference
AP Quick Reference| Pattern | Meaning | AP Exam Tip |
|---|---|---|
| Independent bounds | Inner runs the same number of times each outer pass | Total iterations = outer × inner. |
| Dependent inner bound | Inner bound uses the outer variable | Total iterations form a series, not a product. |
| Row-major 2D traversal | Outer = rows, inner = columns | Use grid.length and grid[r].length. |
| Column-major 2D traversal | Outer = columns, inner = rows | Swap the loop variables to control direction. |
| Pair comparison | Compare each element with every other | Inner loop often starts at i + 1 to avoid duplicates. |
| Pattern printing | Inner builds a line; outer ends it | Use print inside and println after. |
How to master nested loops.
Trace pairs, count carefully, and write 2D traversals on autopilot.
Use the three practice tools below this lesson in order:
- MCQ Practice — make a small (i, j) table for each problem. Mark whether bounds are independent or dependent before counting.
- Java Lab — practise the row-major 2D-array template until you can write it from memory. Solve sum-of-grid, max-of-grid, and count-matches problems.
- FRQ Practice — 2D-array FRQs are the most common place for nested loops. Always use
arr.lengthandarr[r].lengthfor bounds, and add a comment naming the traversal pattern.
If you can sketch the access order on a grid before coding, your nested loops will be correct on the first try.
Practice — attempt these now.
AP-style assessments aligned to this lesson. Time them.