0

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!

3
  • 1
    use the debugger in eclipse. you'll see how the value of first changes Commented Oct 20, 2013 at 19:31
  • Also, note the first-- and the --first in the code. Commented Oct 20, 2013 at 19:31
  • It's not the second <= 5 that makes second go to zero - it's the int second = --first. Commented Oct 20, 2013 at 19:56

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.