The while Statement


Syntax

while (expression)
 statement
 
do
 statement
while (expression);

Notes

The expression must be of arithmetic or pointer type. If an instance of a class is specified for the expression then there must exist an unambiguous conversion from that class to arithmetic or pointer type.

Both forms of the while statement repeatedly execute statement whilst expression evaluates to a non-zero value. That is, the loop is terminated when expression becomes zero. The difference between the two forms is that the first form of while tests the value of expression prior to executing statement; whereas, the latter executes statement first and then tests the value of expression. This implies that the latter form always executes at least one iteration of the loop, whereas the former may not (depending on the initial value of expression).

Examples

Multiple statements may be blocked together to form a single statement using braces, as shown below.

int j=0;
int i=0;
while (i<10)
 {
  j += i;
  i++;
}        // Loop adds numbers 0 - 9, upon exit i==10, j==45.

A similar loop can be used to add numbers 1 to 10 (inclusive) as follows.

int j=0;
int i=0;
do
 {
  i++;
  j += i;
 }
while (i<10);    // Loop adds numbers 1 - 10, upon exit i==10, j==55.