MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
    • Part 1: Selection
    • Part 2: Iteration
      • while Loops
      • for Loops
      • Implementing Selection and Iteration Algorithms
      • Implementing String Algorithms
      • Nested Iteration
      • Informal Run-Time Analysis
      • Unit 2 Part 2 Slides
  • Unit 3: Class Creation
  • Unit 4: Data Collections

Unit 2.11: Nested Iteration

Nested Loops

  • Definition: Nested iteration statements are iteration statements that appear in the body of another iteration statement.
Nested Repetition
  • 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:
    1. The outer loop starts its first iteration.
    2. The inner loop starts and must complete all of its iterations before the outer loop can continue to its next iteration.
    3. The outer loop proceeds to its next iteration.
    4. The inner loop resets and runs through all of its iterations again.
  • Total Iterations: If the outer loop runs nnn times and the inner loop runs mmm times for each outer iteration, the inner body executes n×mn \times mn×m 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.

  1. Outer Loop (Manager): "Start Row 1."
  2. Inner Loop (Worker): Prints Column 1, Column 2, Column 3, Column 4... (Worker is now finished with Row 1).
  3. Outer Loop (Manager): "Move to Row 2."
  4. 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: ****
*/

Nested Loop Diagram

EXCLUSION STATEMENT
  • The break and continue statements, 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 + " ");
        }
    }
}
Privacy Policy | Terms & Conditions