In the Previous section, we learned loops and the different types of loops. In this unit, we will learn how loops can be nested.
If a loop exists inside the body of another loop, it is called a nested loop. The Inner Loop will be executed one time for each iteration of the Outer Loop.
Example
class NestedForLoop { public static void main(String[] args) { for (int i = 0; i < 2; i = i + 1) { // Outer Loop System.out.println("Outer: " + i); for (int j = 0; j < 2; j = j + 1) { // Inner Loop System.out.println(" Inner: " + j); } } System.out.println("After nested for loops"); } |
Outer: 0 Inner: 0 Inner: 1 Outer: 1 Inner: 0 Inner: 1 |
After nested for loops
As shown in the above code, the inner loop is iterated twice for each iteration of the Outer Loop. When i = 2, the outer loop condition is evaluated as false. Therefore, the outer loop will not execute and the statements after the outer loop will be executed now.
Loops may be nested with the same type of loop or another, there is no limitation on order or type. As an example, a while loop can be inside a for loop and vice versa, and a do...while loop can be placed under a while loop.
Example 1: while loop inside a for loop
class NestedLoop { public static void main(String[] args) { for (int i = 0; i < 2; i = i + 1) { // for loop begins System.out.println("Outer For Loop: " + i); int counter = 0;
while (counter < 2) { // while loop begins System.out.println(" Inner While Loop: " + counter); counter = counter + 1; } // while loop ends } // for loop ends } } |
Outer For Loop: 0 Inner While Loop: 0 Inner While Loop: 1 Outer For Loop: 1 Inner While Loop: 0 Inner While Loop: 1 |
Example 2: do...while loop inside a while loop
class NestedLoop { public static void main(String[] args) { int m = 0; while (m < 2) { System.out.println("Outer While Loop: " + m); int n = 0;
do { System.out.println(" Inner Do-While Loop: " + n); n = n + 1; } while (n < 2); m = m + 1; } } }
|
Outer While Loop: 0 Inner Do-While Loop: 0 Inner Do-While Loop: 1 Outer While Loop: 1 Inner Do-While Loop: 0 Inner Do-While Loop: 1 |
Example 3: for loop inside a for loop
class NestedLoop { public static void main(String[] args) { for (int i = 1; i <= 3; i = i + 1) { // Outer Loop System.out.println("Outer For Loop: " + i); for (int j = 0; j < i; j = j + 1) { // Inner Loop System.out.println(" Inner For Loop: " + j); } } } } |
Outer For Loop: 1 Inner For Loop: 0 Outer For Loop: 2 Inner For Loop: 0 Inner For Loop: 1 Outer For Loop: 3 Inner For Loop: 0 Inner For Loop: 1 Inner For Loop: 2 |
For,
i = 1 inner loop iterates 1 time.
i = 2 inner loop iterates 2 times.
i = 3 inner loop iterates 3 times.
Conclusion:
If a loop exists inside the body of another loop, it is called a nested loop.
Loops may be nested with the same type of loop or another, there is no limitation on order or type.
For example, a while loop can be inside a for loop and vice versa, and a do...while loop can be placed under a while loop