# Nested Control Structures

Sean Casey
Ranch Hand
Posts: 625
Given the following code:
public class Loop{
public static void main(String args[]){
outer:
for(int i=0; i<3; ++i){
for(int j=0; j<2; ++j){
if(i == j){
continue outer;
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}
When this is compiled and run the output is as follows:
i=1, j=0
i=2, j=0
i=2, j=1
Could somebody who understands this nested loop walk through each iteration with detail and explain to me how each value is reached. I would really appreciate it. Thanks in advance.

Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Let's call the loop with the 'i' value an outer loop, the one with 'j' an inner loop.
Normally, j would run through all of its iterations once for each iteration of i. So you'd expect:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
and so on.
That 'outer' label adds a dimension to how things flow. It acts as a known marker in the execution of the loop code. When i and j are equal, the statement 'continue outer' means "stop what you're doing, go to the next iteration of the outer loop, and continue."
This code inserts a check for equality, and performs the equivalent of a 'goto' statement to get out of the otherwise routine execution of loops.
-----------------
Michael Ernest, co-author of:
The Complete Java 2 Certification Study Guide
[This message has been edited by Michael Ernest (edited December 25, 2000).]

Sean Casey
Ranch Hand
Posts: 625
I think that I must have misunderstood nested loops, and I've been approaching this the wrong way. I'm really missing something here, I don't understand how the outer loop can reach 2 while the inner loop is still 0. Could you explain that to me?
[This message has been edited by Sean Casey (edited December 25, 2000).]

Sean Casey
Ranch Hand
Posts: 625
I think I got it now. I was overlooking the fact that each time the next iteration of the outer loop executed then the inner loop was intialized to 0 again. For some reason, don't ask me why I thought that for each time the outer loop iterated, so did the inner loop. So I think I'm all set now. Thanks alot for your help Michael. This question had been bothering me for a couple of days. Thanks.

Mahajan Bhupendra
Ranch Hand
Posts: 118
public class Loop{
public static void main(String args[]){
outer:
for(int i=0; i<3; ++i){
for(int j=0; j<2; ++j){
if(i == j){
continue outer;
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}
When this is compiled and run the output is as follows:
i=1, j=0
i=2, j=0
i=2, j=1

Whenever i come across such questions i think in a simple way
i don't know it's correct or not
First think what will be normal o/p i.e. without break or
continue
it should be..
i 0 1 2
j 0 0 0
j 1 1 1
now proceed with the statement..
if(i == j)continue outer;
so whereever i==j remove them..
so o/p will be..
1 0
2 0
2 1
hope u get me..