next up previous
Next: Example Program: Sum of Up: Introduction to C++ Programming Previous: Exercises


The do-while statement

The following example is a version using a do-while statement of the problem considered at the beginning of the Lesson on the while statement. The program has to accept positive numbers entered by a user and to accumulate their sum, terminating when a negative value is entered.

sum = 0.0;
cin >> x;
do {
    sum += x;
    cin >> x;
  }
while (x > 0.0);

Again the accumulator variable sum is initialised to zero and the first value is entered from the user before the do-while statement is entered for the first time. The statement between the do and the while is then executed before the condition x > 0.0 is tested. This of course is different from the while statement in which the condition is tested before the statement is executed. This means that the compound statement between the do and the while would be executed at least once, even if the user entered a negative value initially. This value would then be added to sum and the computer would await entry of another value from the user! Thus do-while statements are not used where there is a possibility that the statement inside the loop should not be executed.

The general form of the do-while statement is:

do
statement
while ( condition ); // note the brackets!

In the do-while statement the body of the loop is executed before the first test of the condition. The loop is terminated when the condition becomes false. As noted above the loop statement is always executed at least once, unlike the while statement where the body of the loop is not executed at all if the condition is initially false. The statement may be a single statement or a compound statement. The effect of a do-while statement can always be simulated by a while statement so it is not strictly necessary. However in some situations it can be more convenient than a while statement.



Subsections
next up previous
Next: Example Program: Sum of Up: Introduction to C++ Programming Previous: Exercises
Peter JB King
1999-08-31