Creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true.
Syntax
while ( condition )
{
statements
}
Parameters
Parameter | Description |
---|---|
condition | Evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements. |
statements | Block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the statement. |
Examples
The following while loop iterates as long as n is less than three.
Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values:
After the first pass: n = 1 and x = 1
After the second pass: n = 2 and x = 3
After the third pass: n = 3 and x = 6
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.