4.4 Nested Iteration

A nested iteration occurs when we have a loop inside of another loop, similar to nested conditional statements in unit 3

When you have one loop inside another, the inner loop has to finish all its rounds before the outer loop moves to the next round. If the inner loop has a “stop” command, it only stops for that round of the outer loop. The next time the outer loop starts a new round, the inner loop starts over.

If you have two nested loops without stops, and the outer one runs n times while the inner one runs m times each time the outer one goes around, the inner loop will run m times n times, which is m * n times in total. This rule also applies if you have more than two nested loops. To find the total number of times the innermost loop runs, just multiply how many times each loop runs per round.

public class NestedLoopsDemo {
    public static void main(String[] args) {
        int n = 3; //numb of times the outside loop runs
        int m = 2; //numb of times the inside loop runs

        //the nested loops
        for (int i = 1; i <= n; i++) {
            System.out.println("Outer loop iteration: " + i);
            for (int j = 1; j <= m; j++) {
                System.out.println("Inner loop iteration: " + j);
            }
        }
    }
}
NestedLoopsDemo.main(null)
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2

Break Statement

The break statement is used to exit a loop prematurely, typically when a certain condition is met. In the case of nested loops, it can be used to break out of the innermost loop.

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Outer loop iteration " + i);
            
            for (int j = 1; j <= 3; j++) {
                System.out.println("Inner loop iteration " + j);
                
                if (i == 2 && j == 2) {
                    System.out.println("Breaking inner loop");
                    break; //break out of the inside loop when i is 2 and j is 2.
                }
            }
        }
    }
}
BreakExample.main(null)
Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 2
Inner loop iteration 1
Inner loop iteration 2
Breaking inner loop
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3

Popcorn HACK

When the targetNumber is found, you can print a message and use the break statement to exit the loop. When it’s not found, you can print a message indicating that the number was not found.

public class BreakHack {
    public static void main(String[] args) {
        int targetNumber = 42; //numb we want
        int[] numbers = {10, 20, 30, 40, 50, 60, 70}; //numb array

        for (int number : numbers) {
            if (number == targetNumber) {
                //if numb is found
                //print message to break out loop
            }
        }
        //if numb isnt found
        //print message showing numb wasnt found if you want
    }
}
BreakHack.main

Continue Statement

The continue statement is used to skip the current iteration of a loop and move to the next iteration. In the case of nested loops, it applies to the innermost loop.

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Outer loop iteration " + i);
            
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    System.out.println("Skipping inner loop iteration " + j);
                    continue; //skip the iteration when i is 2 and j is 2.
                }
                System.out.println("Inner loop iteration " + j);
            }
        }
    }
}
ContinueExample.main(null)
Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 2
Inner loop iteration 1
Skipping inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3

Patterns and Shapes

import java.util.Scanner;

public class InteractivePyramid {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the symbol you want to use: ");
        char symbol = scanner.next().charAt(0);

        System.out.print("Enter the number of rows for the pyramid: ");
        int numRows = scanner.nextInt();

        for (int i = 1; i <= numRows; i++) {
            //print space before the symbol
            for (int j = 1; j <= numRows - i; j++) {
                System.out.print(" ");
            }

            //print
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print(symbol);
            }

            System.out.println(); //next line
        }
        scanner.close();
    }
}
InteractivePyramid.main(null)
Enter the symbol you want to use: Enter the number of rows for the pyramid:         o
       ooo
      ooooo
     ooooooo
    ooooooooo
   ooooooooooo
  ooooooooooooo
 ooooooooooooooo
ooooooooooooooooo

Hacks

  1. Modify pyramid code:
  • Create different patterns (other then pyramid) by modifying nested loop structure
  1. Questions
  • What is a nested iteration, continue statement, and break statement (in your own words)?
  • Create a simple example of a continue statement or break statement