Unit 2.11: Nested Iteration
Nested Loops
- Definition: Nested iteration statements are iteration statements that appear in the body of another iteration statement.
- Nested loops model multi-dimensional data or repetitive processes within another repetition. The inner loop must complete its entire cycle for every single iteration of the outer loop.
- Execution Flow:
- The outer loop starts its first iteration.
- The inner loop starts and must complete all of its iterations before the outer loop can continue to its next iteration.
- The outer loop proceeds to its next iteration.
- The inner loop resets and runs through all of its iterations again.
- Total Iterations: If the outer loop runs times and the inner loop runs times for each outer iteration, the inner body executes times. Note that in many algorithms, the number of inner iterations may depend on the current value of the outer loop control variable.
The Narrative: Mental Models for Nested Loops
To understand nested loops, it helps to use a narrative or a "mental model."
1. The Clock Analogy
Think of the hands of a clock. For every one hour that the "outer" hour hand moves, the "inner" minute hand must complete all 60 minutes. The minute hand resets to zero every time a new hour begins.
2. The Grid Narrative (Rows and Columns)
When printing a grid, the outer loop acts like a manager deciding which "row" you are currently standing on. The inner loop acts like a worker filling in every "column" or star in that specific row.
- Outer Loop (Manager): "Start Row 1."
- Inner Loop (Worker): Prints Column 1, Column 2, Column 3, Column 4... (Worker is now finished with Row 1).
- Outer Loop (Manager): "Move to Row 2."
- Inner Loop (Worker): Resets and prints Column 1, Column 2, Column 3, Column 4... (Worker is now finished with Row 2).
Examples
Nested for Loops: Printing a Grid
public class NestedLoopExample {
public static void main(String[] args) {
// Outer loop: The "Manager" deciding which row we are on
for (int row = 1; row <= 3; row++) {
System.out.print("Row " + row + ": ");
// Inner loop: The "Worker" filling in 4 stars for that row
for (int col = 1; col <= 4; col++) {
System.out.print("*");
}
// Once the worker is done, we print a newline to start the next row
System.out.println();
}
}
}
/* Output:
Row 1: ****
Row 2: ****
Row 3: ****
*/

- The
breakandcontinuestatements, which can be used to alter the flow of a loop, are not part of the AP Computer Science A course and will not be on the AP Exam. However, they are commonly used in general programming for early termination or skipping iterations.
Controlling Loop Flow: break and continue
As introduced in Unit 2.8, you can use break and continue to gain more control over your loop's execution. In nested loops, these statements only affect the innermost loop in which they are placed.
The break Statement
The break statement immediately terminates the innermost loop it is in. Execution continues at the first statement following the terminated loop.
Task: Exiting a loop early using the break statement.
public class BreakExample {
public static void main(String[] args) {
int[] numbers = {12, 17, 25, 33, 40, 54};
for (int num : numbers) {
System.out.println("Checking: " + num);
if (num % 5 == 0) {
System.out.println("Found the first number divisible by 5: " + num);
break; // Exit the loop immediately
}
}
System.out.println("Loop finished.");
}
}
The continue Statement
The continue statement skips the remaining code in the current iteration of the loop and proceeds directly to the next iteration (triggering the update statement in a for loop).
Task: Skipping specific values using the continue statement.
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers, go to i++
}
System.out.print(i + " ");
}
}
}