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
is equivalent to
As you can see the
count = count + 1has no effect, since the value ofcountis overwritten in the last line, and ifcountis initially 0, then the result will obviously becount = 0 + 0🙂