Nested Loop in Java

In this article, you will learn about nested loops and how it works with the help of examples.

If a loop exists inside the body of another loop, it's called nested loop. Here's an example of nested for loop.

for (int i = 1; i <= 5; ++i) {

   // codes inside the body of outer loop

   for (int j = 1; j <=2; ++j) {
      // codes inside the body of both outer and inner loop
   }

   // codes inside the body of outer loop
}

Here, a for loop is inside the body another for loop.

It should be noted that, you can put one type of loop inside the body of another type. For example, you can put a while loop inside the body of a for loop.


Example 1: Java Nested for Loop

class NestedForLoop {
   public static void main(String[] args) {
      
      for (int i = 1; i <= 5; ++i) {

         System.out.println("Outer loop iteration " + i);

         for (int j = 1; j <=2; ++j) {
            System.out.println("i = " + i + "; j = " + j);
         }
      }
   }
}

When you run the program, the output will be:

Outer loop iteration 1
i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2

Here, the outer loop iterates 5 times. In each iteration of outer loop, the inner loop iterates 2 times.

Let's take another example.


Example 2: Java Nested Loop

class NestedLoop {
   public static void main(String[] args) {
      
      int i = 1;
      
      while (i <= 5) {
       
         System.out.println("Outer loop iteration " + i);

         for (int j = 1; j <= 2; ++j) {
            System.out.println("i = " + i + "; j = " + j);
         }
         
         ++i;
      }
   }
}

The output of this program and above program is same.


Example 3: Program to create a pattern

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Here is a program to create the above pattern using nested loops.

class Pattern {
   public static void main(String[] args) {
      
      int rows = 5;
      
      for(int i = 1; i <= rows; ++i)
      {
          for(int j = 1; j <= i; ++j)
          {
             System.out.print(j + " ");
          }
          System.out.println("");
      }
   }
}