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?
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.
551 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
542 Uncaught (inpromise) Error on Electron: An object could not be cloned
733 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
549 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.