简体   繁体   中英

How do I find the output of the following code fragment in Java?

I have the following code fragment, which yields a sum of 16.

int sum = 1;
for (int i = 0; i <= 5; sum = sum + i++)
System.out.println(sum);

From my understanding of sum = sum + i++ and for loops in general, my thought process for the loop would be like this:

  • 0th loop: sum = 1 (do nothing)
  • 1st loop: sum = 1 + 1 (uses sum = 1 from previous iteration )
  • 2nd loop: sum = 2 + 2
  • 3rd loop: sum = 4 + 3
  • 4th loop: sum = 7 + 4
  • 5th loop: sum = 11 + 5

Obviously, there is an error in my logic. Could you please explain why the sum would be 16?

Change System.out.println(sum); to include the loop number as well. Also, don't forget to print the values after your loop.

int sum = 1;
for (int i = 0; i <= 5; sum = sum + i++) {
    System.out.printf("loop=%d, sum=%d%n", i, sum);
}
System.out.printf("after loop, sum=%d%n", sum);

Output

loop=0, sum=1
loop=1, sum=1
loop=2, sum=2
loop=3, sum=4
loop=4, sum=7
loop=5, sum=11
after loop, sum=16

Which I trust explains both how and why sum is 16 after the loop.

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