I'm learning a simple Java iteration, but I'm not sure about the increment or decrease operator

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

public class Main {
    public static void main(String[] args) 
        int i=1,sum=0;

        while(i<=6) {
            sum+=i++;     }

        System.out.println ("the sum of 1 to 6 is "+sum");
        }
}

It's a code to find the sum of 1 to 6, but I don't understand it well. Doesn't that sentence sum+=i++ mean 1+1 2+1 3+1 4+1 5+1 6+1 -> 2+3+4+5+6+7? I don't know how that code is interpreted as 1+2+3+4+5+6. I understood that the repetition sentence that starts with while(i<=6) means from 1 to 6, but is this also wrong?

java

2022-09-20 08:40

1 Answers

The posterior operator i++ is the operator that adds 1 to the variable i immediately after executing a syntax.

sum += i++;

The above syntax can soon be replaced with the following equivalent syntax::

sum = sum + i;
i = i + 1;

If you repeat these operations for i <= 6, the sum value will be 21.

assert sum == 0 + 1 + 2 + 3 + 4 + 5 + 6; // 21; true value

You can also use the convenient for(...){} statement instead of the while(...){} statement.

int sum = 0;
for (int i = 1; i <= 6; i++)
    sum += i;
System.out.println ("the sum of 1 to 6 is " + sum");
// or more simply
int sum = 0;
for (int i = 1; i <= 6; sum += i++);
System.out.println ("the sum of 1 to 6 is " + sum");

Note: The assert keyword is a keyword that increases the reliability of the program by affirming that the conditional expression that follows is true.


2022-09-20 08:40

If you have any answers or tips


© 2022 pinfo. All rights reserved.