4.4: Nested Iteration

Learning Objective: Represent nested iteration processes

Essential Knowledge:

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

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

(write your guess here)

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)?

(Write your guess here)

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 number 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? 4

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

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

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

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? 5

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

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

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

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? We can’t tell, since it’s based on rng

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

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

In the code above, how many times will the statement #2 execute? 27

Rewrite the code above to be more effecient based on execution count.

for (int k = 0; k < 135; k+=5){
    System.out.print(k); // Statement #2
}