Forums Register Login

for loop question

+Pie Number of slices to send: Send
where exactly does the var i increment in this code:
public class Myfor {
public static void main(String argv[]) {
int i;
int j;

outer: for ( i=1 ; i<3 ; i++ )

inner: for ( j=1 ; j<3 ; j++ ) {
if (j==2) continue outer;
System.out.println( i + " " + j );
}
}
}
the output is : 1 1
2 1
But I just figure it out!
where is i & j incrementing? why a 2 and a 1?
help please!!!
+Pie Number of slices to send: Send
Hi Donald:
outer: for ( i=1 ; i<3 ; i++ )
i is incremented with the the ++ postfix operator at the end of every iteration of the for loop. Let's analyze it:

When the outer loop begins, i = 1. Then the inner loop begins and j = 1. Next the if condition is tested and evaluates false so the System.out prints the values of i and j or 1 1. Now j is incremented to be 2. The next iteration of inner begins and the if now evaluates true which causes the outer loop to complete its iteration, incrementing i in to process to now be 2. The inner loop now starts all over, j is 1 again and the same exact thing happens except that now i is 2, so the System.out prints 2 1. On the next iterarion of inner j becomes 2 and the if is true again causing outer to finish the current iteration and incrementing i to 3 but alas the conditional of the outer loop is i < 3 so the outer loop finishes and we are thru.
Michael Morris
+Pie Number of slices to send: Send
for loop execution is as follows:
1. initialization expression executes
2. loop condition is evaluated: if true,
body of the for statement is executed,
otherwise the for statement is complete
3. increment expression is evaluated, repeat step 2
continue causes a "short circuit" of the body execution and typically goes straight to step 3 above. If a label is involved, then the short circuiting goes all the way back to the for statement after the label.
In your example:
1. i is initialized to 1
2. (i < 3) is true
3. j is initialized to 1
4. (j < 3) is true
5. if (j == 2) is false
6. output: "1 1"
7. j++ evaluated; j is now 2
8. if (j == 2) is true
9. continue outer; short-circuits normal loop execution
10. i is incremented; i is now 2
11. outer loop condition evaluated: (i < 3) ==> 2 < 3 ==> is true
12. j is initialized to 1
13. if (j == 2) is false
14. output: "2 1"
15. j++ evaluated; j is now 2
16. if (j == 2) is true
17. continue outer; short-circuits normal loop execution; inner for loop terminates
18. i is incremented; i is now 3
19. outer loop condition evaluated: (i < 3) ==> (3 < 3) ==> false; outer loop terminates
Self destruct mode activated. Instructions for deactivation encoded in this tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 889 times.
Similar Threads
Loop Problem
please help
Help with Continue ..
Label question
marcus green mock
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 20:18:39.