Menu
Topics Index
...
`

Nested for loop - Java Example Program


Nested for loop
class NestedForLoopExample
{
    public static void main(String arg[])
    {
        for(int outer = 0; outer <= 2;  outer++)
        {
            for(int inner = 0; inner <= 3; inner++)
            {
                System.out.println(outer + "   " + inner);
            }
            System.out.println();
        }      
    
    }
}
OUTPUT

0 0
0 1
0 2
0 3

1 0
1 1
1 2
1 3

2 0
2 1
2 2
2 3

DESCRIPTION

In the above example outer and inner are initialized to zero. For every increment of outer (i.e outer = 0, 1, 2) loop, the inner loop executes four times (i.e inner = 0, 1, 2, 3). So, we get the output as shown above. Note that the outer loop's condition is outer <= 2 where as for inner loop it is inner <= 3.

THINGS TO TRY
  • Change the end value for outer loop to 5 instead of 2 i.e. outer <= 2; to outer <= 5; and see the output.
  • Change the end value for inner loop to 1 instead of 3 i.e. inner <= 3; to inner <= 1; and see the output.
  • Add one more inner loop 2 called deepest - inside inner loop with counter as deepest and print the values outer, inner and deepest.

© meritcampus 2019

All Rights Reserved.

Open In App