Nested iteration means putting one loop inside another loop. The key rule is that the inner loop runs through all of its iterations every time the outer loop runs once. For AP Computer Science A, trace both loop variables together so you can predict output, counts, and off-by-one behavior.
Why This Matters for the AP Computer Science A Exam
Nested loops show up in the parts of the exam that ask you to predict output and trace execution step by step. On multiple choice, you will be given a code segment with two loops and asked what it prints or what value a variable ends with. You will also see questions that ask you to complete missing code so a nested loop meets a description, and questions about why a loop will not compile or work as intended.
For free-response code writing, you may need to write iterative statements, and nested loops are a common tool when a problem involves repeated work for each item in a group. Being able to figure out the starting conditions a loop needs to work correctly is also part of what this topic supports. Later in the course, nested loops become a main tool for working with 2D arrays, so getting comfortable now pays off.

Key Takeaways
- The inner loop finishes all of its iterations before the outer loop moves to its next iteration.
- If the outer loop runs A times and the inner loop runs B times, the body runs A times B in total.
- Each loop needs its own control variable, and mixing them up is a frequent source of bugs.
- Inner loop bounds can depend on the outer loop variable, which creates triangle-style patterns.
- Trace nested loops by writing down both loop variables at every step instead of guessing.
- Off-by-one errors can hide in either loop, so check each loop's bounds separately.
Core Idea: How Nested Loops Execute
When one loop sits inside another, the inner loop runs to completion for every single pass of the outer loop. This is the most important thing to understand.
</>Javafor (int outer = 1; outer <= 3; outer++) { for (int inner = 1; inner <= 2; inner++) { System.out.println("Outer: " + outer + ", Inner: " + inner); } }
This produces:
</>CodeOuter: 1, Inner: 1 Outer: 1, Inner: 2 Outer: 2, Inner: 1 Outer: 2, Inner: 2 Outer: 3, Inner: 1 Outer: 3, Inner: 2
Notice how the inner loop variable cycles through all its values (1, 2) for each value of the outer loop variable.
A useful mental model
Think of nested loops like a digital clock. The outer loop is the hours and the inner loop is the minutes. For every hour, the minutes count all the way through before the hour advances. That is exactly how the inner loop drains its full cycle before the outer loop steps forward.
Counting total iterations
If the outer loop runs A times and the inner loop runs B times, the total number of times the inner body runs is A times B.
- Outer loop: 5 iterations
- Inner loop: 3 iterations
- Total body executions: 5 times 3 = 15
This connects directly to counting statement executions, which is the focus of the next topic in this unit.
Keep loop variables distinct
Each loop has its own control variable. Descriptive names make your code easier to read and reduce mistakes.
</>Javafor (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { // Process position (row, col) } }
Code Examples
Basic pattern generation
</>Javapublic class PatternGeneration { // Print a rectangle of stars public static void printRectangle(int rows, int cols) { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { System.out.print("* "); } System.out.println(); // New line after each row } } // Print a right triangle public static void printTriangle(int size) { for (int row = 1; row <= size; row++) { for (int star = 1; star <= row; star++) { System.out.print("* "); } System.out.println(); } } public static void main(String[] args) { System.out.println("Rectangle:"); printRectangle(3, 4); System.out.println("\nTriangle:"); printTriangle(4); } }
Notice that in printTriangle, the inner loop bound depends on the outer variable row. That is what creates the growing triangle shape instead of a full rectangle.
Comparing pairs of elements
A common nested-loop pattern starts the inner loop at i + 1 so each pair is checked once.
</>Javapublic class ComparisonProblems { // Find all pairs in an array that sum to a target public static void findPairs(int[] array, int target) { System.out.println("Pairs that sum to " + target + ":"); for (int i = 0; i < array.length; i++) { for (int j = i + 1; j < array.length; j++) { // Start j at i+1 to avoid duplicates if (array[i] + array[j] == target) { System.out.println(array[i] + " + " + array[j] + " = " + target); } } } } // Count inversions (how many pairs are out of order) public static int countInversions(int[] array) { int count = 0; for (int i = 0; i < array.length; i++) { for (int j = i + 1; j < array.length; j++) { if (array[i] > array[j]) { // i comes before j but has larger value count++; } } } return count; } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; findPairs(numbers, 5); // 1+4, 2+3 int[] unsorted = {3, 1, 4, 2}; System.out.println("Inversions: " + countInversions(unsorted)); // 4 } }
Multiplication table generator
</>Javapublic class MultiplicationTable { public static void printTable(int size) { for (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) { System.out.print((row * col) + "\t"); } System.out.println(); } } public static void main(String[] args) { printTable(5); } }
How to Use This on the AP Computer Science A Exam
Code Tracing
When you trace nested loops, work through them in order: hold the outer variable steady and run the inner loop all the way through before letting the outer variable change. Write down both loop variables at each step. Trying to skip ahead is where most tracing mistakes come from.
Free Response
When a problem asks you to write iterative statements, nested loops are a natural fit when there is repeated work for each item in a group. Read the specification closely. Underline keywords, return types, and parameters so you set up your loop bounds correctly. If the inner work depends on the current outer value, your inner loop bound may need to reference the outer variable.
Common Trap
Predicting output is much easier if you remember the inner loop drains completely before the outer loop advances. For pattern problems, decide whether the inner loop should run a fixed number of times or a number that depends on the outer variable.
Checking Initial Conditions
Some questions ask what must be true for a loop to behave as described. Check the starting values of both control variables and confirm the bounds match the size of whatever you are processing. A loop body runs zero times if its condition is false on the first check, so an inner loop can be skipped entirely on some outer passes.
Common Misconceptions
- The inner loop does not run just once per outer pass. It restarts and runs its full cycle every time the outer loop iterates.
- Total work is not the outer count plus the inner count. It is the outer count times the inner count, since the inner body repeats for every outer pass.
- Swapping the two loop variables when accessing a grid, like writing
array[col][row]instead ofarray[row][col], changes which element you reach and can cause errors. Keep track of which variable means what. - Using
<=with a count or length when you meant<is an off-by-one error, and in nested loops it can happen in either loop. Check both bounds separately. - Nested loops are not always the best tool. If you do not actually need to compare every combination, a single loop or a different approach may be faster and clearer.
Related AP Computer Science A Guides
Vocabulary
The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.Term | Definition |
|---|---|
inner loop | The iteration statement contained within the body of another iteration statement that executes completely for each iteration of the outer loop. |
iteration statement | A control structure that repeats a block of code multiple times based on a condition. |
nested iteration | Iteration statements that appear within the body of another iteration statement, where the inner loop completes all its iterations before the outer loop advances to its next iteration. |
outer loop | The iteration statement that contains another iteration statement within its body. |
Frequently Asked Questions
What is nested iteration in AP Computer Science A?
Nested iteration means placing one loop inside another loop. The inner loop runs all the way through for each single iteration of the outer loop.
How do nested loops execute?
The outer loop starts, then the inner loop completes all of its iterations. Only after the inner loop finishes does the outer loop move to its next iteration.
How do you count total iterations in nested loops?
If the outer loop runs A times and the inner loop runs B times for each outer pass, the inner body runs A times B total. If the inner bound changes, count each outer pass separately.
Why do nested loops need different control variables?
Each loop needs its own control variable so you can track the outer and inner loops separately. Reusing or mixing up variables often causes incorrect output or bounds errors.
Where do nested loops show up on the AP CSA exam?
Nested loops appear in output tracing, loop-bound questions, string or array processing, and later 2D array work. You may need to predict output or write nested iteration code.
What is a common nested loop mistake?
A common mistake is assuming the inner loop runs once per outer loop. It actually restarts and completes its full cycle for every outer-loop iteration.