1
votes

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
You need to read up about the pre and post increment operators. - cup
Currently the calculation is basically 1 + 2 + 3 + 4 + 5 + 6. "And why not ++i?" - When you change it to that, what happens to the result? - David
Right. The value of i++ in an expression is the value of i. As a side effect, it also bumps the value stored in i, but the bumped value isn't part of the expression. The value of ++i in an expression is i+1. - Tim Roberts

1 Answers

0
votes

the answer is 21 because we add each iteration of the loop in the sum. so at each verification if a number is less than or equal to <=6 we add each in the variable sum. so the increment is after verification and not make the post incrementention. #JAVA