I am having trouble understanding the following code block.
int count = 0;
for (int i = 0; i < 3; i++){
count += (count++);
System.out.println("count = " + count);
System.out.println("i = " + i);
}
My understanding is that the loop runs three times preforming the following
count = count + count
count = 1 + count
This translates to the following as count initially is 0:
count = 0 + 0
count = 1 + 0 = 1
count = 1 + 1 = 2
count = 1 + 2 = 3
count = 3 + 3 = 6
count = 6 + 1 = 7
The output is below, and count is printed as 0.
count = 0
i = 0
count = 0
i = 1
count = 0
i = 2
Could someone explain this to me? Thanks
The confusing part is this line --
count+ = (count++);
This effectively is doing this --
count = count + ( count++ );
So, the value of (count++)
for the equation is 0, the post-increment happens after, but then count
gets assigned a 0, so the post-increment is thrown away.
This happens 3 times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With