Greetings,
I have another question regarding a "for" loop. Take a look at the following program:
class ForLoop{
public static void main(
String[]args){
int i;
OuterLoop: for(i = 3; i > 0; i--){
InnerLoop: for(int j = 0; j < 4; j++){
System.out.println("i = " + i + " and j = " + j);
if(i == j)
break InnerLoop;
}
}
}
}
The output is:
i = 3 and j = 0
i = 3 and j = 1
i = 3 and j = 2
i = 3 and j = 3
i = 2 and j = 0
i = 2 and j = 1
i = 2 and j = 2
i = 1 and j = 0
i = 1 and j = 1
I'm trying to make sure that i'm understanding why i get the output i did. My understanding is when starting out, i = 3, it goes through the OuterLoop, the condition is checked (true), and it is then passed into the value of 'i':
i = 3
Next, in the InnerLoop, j starts out as '0' and goes through the loop, the condition is checked(true) and is passed into the value of 'j':
j = 0
Looking at the if statement, the lnnerLoop continues through the loop, increments according to the rule until 'j' becomes '3':
i = 3 and j = 1
i = 3 and j = 2
i = 3 and j = 3
(i == j) <-------- code breaks when i = 3 and j = 3
The InnerLoop stops ("break InnerLoop") and the OuterLoop starts over as i decrements (i--) and becomes 2, goes through the OuterLoop again, the condition is checked (true) and passed into 'i' again:
i = 2
Then the InnerLoop continues it's loop as j starts out again as 0, increments according to the rule until 'j' becomes '2':
i = 2 and j = 0
i = 2 and j = 1
i = 2 and j = 2
(i == j) <-------- code breaks when i = 2 and j = 2
.....and so on and so forth.
Am i correct in my assessment? Thanks in advance.