0

Could someone explain how the flow of control works with a nested for loop?

for (initialize; condition; increment) 
    for (initialize; condition; increment)
       statement;

I know a single for loop is:
initialize --> condition --> statement --> increment--> condition -->.......

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

The contents of a for loop can be a statement or a block. Either way the contents are executed as many times as the (initialize; condition; increment) specifies.

for (initialize1; condition1; increment1)
    for (initialize2; condition2; increment2)
       statement;

Here the first for executes the following code as many times as it should:

for (initialize2; condition2; increment2)
       statement;

which inturn executes statement appropriately before going back to the outer for loop for another execution.
eg

for (int i = 0; i<3)
   for (int j = 0; j<2; j++)
      System.out.println(i + " " + j);

will give the following output
0 0
0 1
1 0
1 1
2 0
2 1

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.