public class Main {
public static void main(String[] args) {
int i=1,sum=0;
while(i<=6) {
sum+=i++;
}
System.out.println(sum);
}
}
this is java eclipse code, and it prints 21 normally But i don't understand that "sum += i++; " code. I understood the meaning of that code as, 1+1 2+1 3+1 4+1 5+1 6+1 -> 2+3+4+5+6 -> 20. How is that code calculated in a while loop? And why not ++i?
1 + 2 + 3 + 4 + 5 + 6
. "And why not ++i?" - When you change it to that, what happens to the result? - Davidi++
in an expression is the value ofi
. As a side effect, it also bumps the value stored ini
, but the bumped value isn't part of the expression. The value of++i
in an expression isi+1
. - Tim Roberts