Reputation: 3
For my Java practice midterm, we need to write the exact output of a line of code, in this case, a for loop. Here's the code:
for(int first = 3; first > 0; first--)
for(int second = --first; second <= 5; second++)
System.out.println(first + " " + second);
So I figured the output to be:
2 2
2 3
2 4
2 5
But when I run it in Ecplipse it comes out with:
2 2
2 3
2 4
2 5
0 0
0 1
0 2
0 3
0 4
0 5
I understand how "second" would go from 5 to 0 because of "second <= 5" but I don't see how "first" also resets to 0.
I searched all over for an answer, but couldn't find one. Any help on how this works would be great. Thanks!
Upvotes: 0
Views: 93
Reputation: 1499740
You're decrementing first
twice: once each time the outer loop iterates, and once each time the inner loop starts iterating.
So after printing 2 5
it hits the end of the inner loop, and hits the first--
from the outer loop. Then as it goes back into the inner loop again, it hits int second = --first
before printing anything else. Hence going from 2 to 0.
Personally I would try to avoid statements like int second = --first;
- the side-effects often cause confusion.
Upvotes: 3