Menu
Topics Index
...
`


Control Statements > Iteration statements (Loops) >
Siva Nookala - 11 Apr 2016
Placing one for loop with in the body of another for is called nested for loop. This kind of nesting is commonly used in programming. Having loops inside loops, which are inside another loop is a required to achieve the programming tasks.

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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.