Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Nested loops

Java Programming Language Nested Loops

In Java programming, a loop of one type can be used inside any another or same type of loop. That is a loop inside another loop. Such loops are known as nested loops.

Example

The while loop can be used inside another for loop

The for loop can be used inside another for loop

The do-while loop can be used inside another while loop

The for loop can be used inside another do-while loop

The for loop can be used inside another while loop, etc.

Example No. 1

class NestedLoopDemo2 
{
    public static void main(String args[])
    {
        int i,j;
        for(i=1;i<=3;i++)
        {
            j = 1;
            while(j<=3)
            {
                System.out.println(i+" "+j);
                j++;
            }
            System.out.println();
        }
    }
}

Output

1 1
1 2
1 3

2 1
2 2
2 3

3 1
3 2
3 3

Example No. 2

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

Output

1 1
1 2
1 3

2 1
2 2
2 3

3 1
3 2
3 3

 

Leave a reply