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:
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.