Nested For Loops
First, the rules to these loops do not change. We are sticking one loop inside another. while(condition) { // loop body } do { // loop body }while(condition); for(integer initialization; condition; iteration) { // loop body }while(condition);
while(condition) { while(condition) { // loop body } do { do { // loop body }while(condition); for(integer initialization; condition; iteration) { for(integer initialization; condition; iteration) { // loop body }
Example 1 int n = 10; while(n == 10) { while(n > 0) { n--; }
Example 2 int n = 10; do { do { n--; }while(n > 0); }while(n == 10);
Example 3 for(int k = 0; k < 10; k++) { for(int j = 0; j < 10; j++) { System.out.println(“Hello World”); }
Example 3 continued for(int k = 0; k < 10; k++)// scope of variable k is within this entire loop { for(int j = 0; j < 10; j++) // j is only within this loop { System.out.println(“Hello World”); } System.out.println(j); // you cannot do this, j is “dead” }
Once a loop begins and encounters another loop, the inner loop now executes until it finishes before the outer loop continues. for(int k = 0; k < 10; k++) { for(int j = 0; j < 10; j++) { System.out.println(“Hello World”); } // Loop in red finishes 10 times before the outer loop can // continue.
What’s the output? int j = 0; while(j < 5) { for(int s = 0; s < 5; s++) { System.out.println(“Hello”); } System.out.println(“World”); j++; }
What’s the output? int j = 0; do { System.out.println(“World”); for(int s = 0; s < 5; s++) { System.out.println(“Hello”); } j++; }while(j < 10);
What’s the output? for(int k = 0; k < 5; k++) { for(int j = 0; j < 5; j++) { System.out.println(“Hello World”); } System.out.println(“Hello World”); }
Exercise 1 Print “Hello World” 50 times using two nested for loops. Let outer loop run 10 times and inner loop run 5 times.
Exercise 2 Ask for a user input of a number between Enter a while loop that will loop exactly the number of times of the input. Inside this while loop, enter a number a for loop that will display “Hello world” 5 times.
Exercise 3 Create this Rectangle: It’s a 10 x 5 that prints 10 consistently
Exercise 4 Create the triangle
Exercise 5 Create the Pyramid Keep going until you reach 10.