by Dinesh Thakur

Nested loop means one loop inside the other. When a loop is written inside the other loop, a condition is essential to maintain: the inner loop will not cross the boundary of the outer loop. That is, the inner loop will begin and end inside the outer loop. We can have any number of loops one inside the other.

The inner loop executes faster then the outer loop as shown

Let's look at the following examples:

 

Print the output as:

 

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

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

 

Nested For Loop

 

Above program uses nested (one inside other) loops. Loop j is used inside loop i.

The inner loop executes faster then the outer loop. Secondly, the inner loop will not cross the boundary of the outer loop. That is, the inner loop will begin and end inside the outer loop.

The outer loop has counter i starting from 1 to 5. The inner loop j will have the value from 1 to i. So the loop j will run only for one time and will print 1 on the screen. In the next iteration, the value of counter i will be 2 which makes the loop j to execute for 2 times printing 1 and 2 and so on. On one of another example we can see.

Print the output as:

1

1          2

1          2          3

1          2          3          4

1          2          3          4          5

class NestedForLoop2

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

Nested For Loop in Java Example