In this program, the while statement is
-
- while (val <= 10) {
- sum += val;
- ++val;
- }
The condition uses the less-than-or-equal operator (the <= operator) to compare the current value of val and 10. As long as val is less than or equal to 10, the condition is true. If the condition is true, we execute the body of the while. In this case, that body is a block with two statements:
- {
- sum += val;
- ++val;
- }
A block is a sequence of zero or more statements enclosed by curly braces. A block is a statement and may be used wherever a statement is required. The first statement in this block uses the compound assignment operator (the += operator). This operator adds its right-hand operand to its left-hand operand and stores the result in the left-hand operand. It has essentially the same effect as writing an addition and an assignment:
- sum = sum + val;
Thus, the first statement in the block adds the value of val to the current value of sum and stores the result back into sum.
The next statement
- ++val;
uses the prefix increment operator (the ++ operator). The increment operator adds 1 to its operand. Writing ++val is the same as writing val = val + 1.
After executing the while body, the loop eva luates the condition again. If the (now incremented) value of val is still less than or equal to 10, then the body of the while is executed again. The loop continues, testing the condition and executing the body, until val is no longer less than or equal to 10.
Once val is greater than 10, the programfalls out of the while loop and continues execution with the statement following the while. In this case, that statement prints our output, followed by the return, which completes our main program.