Next: Example while loop: Printing
Up: Introduction to C++ Programming
Previous: Exercises
The following piece of C++ illustrates a while statement. It
takes a value entered by the user and as long as the user enters positive
values it accumulates their sum. When the user enters a negative
value the execution of the while statement is terminated.
sum = 0.0;
cin >> x;
while (x > 0.0)
{
sum += x;
cin >> x;
}
The variable sum which is to hold the accumulated sum is
initialised to zero. Then a value for x is entered so that
x has a value before being tested in the condition
x > 0.0. Note that the value of x is updated in
the body of the while loop before returning to test the condition
x > 0.0 again.
The general form of a while statement is:
while ( condition )
statement
While the condition is true the statement is repeatedly
executed. The statement may be a single statement (terminated
by a semi-colon) or a compound statement. Note the following points:
while statement. Thus all variables etc. used in
the condition must have been given values before the while
statement is executed. In the above example the variable
x was given a value by entering a value from the user.x was given a new
value inside the body of the while statement by entering the next value
from the user.while
loop would take place.