7 min read

4.4 Nested Iteration

Essential Knowledge:

  • Nested iteration is when an _____ statement appears inside the body of another iteration statement
  • The inner loop must run complete ___ of its iterations before the outer loop can continue.

Before uncommenting the code, guess what the output will look like:

public class NestedLoops{

    public static void main(String[] args){

        // for (int outer = 1; outer < 5; outer++){

        //     for (int inner = 1; inner < 3; inner++){
                
        //         System.out.print(inner + " ");
        //     }

        //     System.out.println();

        // } 

    }
}

NestedLoops.main(null)

What will the output of the code above be if we switch the loop headers (the stuff inside of the for loop)?

After making a prediction actually switch the loop headers for yourself. What do you notice about the output compared to the output before the change?

4.5 Informal Code Analysis

Essential Knowledge:

  • A statement exectution count indicates the __ of times a statement is executed by the program
for (int outer = 0; outer < 3; outer++){
    for (int inner = 0; inner < 4; inner++){
        // statement #1
    }
}

In the code above, how many times will the inner loop execute when outer = 0? __
In the code above, how many times will the inner loop execute when outer = 1? __

In the code above, how many times will the inner loop execute when outer = 2? __
In the code above, how many times will the inner loop execute in total? __

for (int outer = 5; outer > 0; outer--){
    for (int inner = 0; inner < outer; inner++){
        // statement #1
    }
}

In the code above, how many times will the inner loop execute when outer = 5? __

In the code above, how many times will the inner loop execute when outer = 4? __

In the code above, how many times will the inner loop execute when outer = 3? __

In the code above, how many times will the inner loop execute in total? __

int k = 0;
while (k < 5){
    int x = (int)(Math.random()*6) + 1;
    while (x != 6){
        //statement #1
        x = (int)(Math.random()*6) + 1;
    }
    k++;
}

In the code above, how many times will the statement #1 execute? __

for (int k = 0; k < 135; k++){
    if (k % 5 == 0){
        System.out.println(k); // Statement #1
    }
}

In the code above, how many times will the statement #1 execute? __

Rewrite the code above to make it more efficient using a for loop.