while statements execute as long as a specified condition evaluates to true:
while statement syntax:
If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.
The condition test occurs before the loop statements are executed. If the condition returns true, the loop statements are executed, and the condition is re-tested. If the condition returns false, loop execution stops, and the statement following while executes.
Example—while loop that repeats as long as n < 3:
With each iteration, the loop increments n and adds that value to x. Therefore, x and n obtain the following values:
After the third pass, the condition n < 3 is no longer true, so the loop terminates.
Example—while loop that never terminates; that is, the loop executes forever because the condition never becomes false: