简体   繁体   中英

Need help on this for loop

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM