The do-while Loop in C++

A do-while loop is the same as a while loop except that it executes the loop body first and then checks the loop continuation condition.

The do-while loop is a variation of the while loop. Its syntax is as follows:

do

{

// Loop body;

Statement(s);

} while (loop-continuation-condition);

Its execution flowchart is shown in Figure 5.2.

The loop body is executed first. Then the loop-continuation-condition is evalu­ated. If the evaluation is true, the loop body is executed again; otherwise the do-while loop terminates. The major difference between a while and a do-while loop is the order in which the loop-continuation-condition is evaluated and the loop body executed. The while and do-while loops have equal expressive power. Sometimes one is more convenient than the other. For example, you can rewrite the while loop in Listing 5.5 using a do-while loop, as shown in Listing 5.7.

Figure 5.2 The do-while loop executes the loop body first, then checks the loop-continuation-condition to determine whether to continue or terminate the loop.

Listing 5.7 TestDoWhile.cpp

1 #include <iostream>

2 using namespace std;

3

4 int main()

5 {

6    // Keep reading data until the input is 0

7    int sum = 0;

8    int data = 0;

9

10    do

11    {

12       sum += data;

13

14       // Read the next data

15        cout << “Enter an integer (the input ends ” <<

16        “if it is 0): “;

17         cin >> data;

18     }

19     while (data != 0);

20

21     cout << “The sum is ” << sum << endl;

22

23     return 0;

24 }

What would happen if sum and data were not initialized to 0? Would it cause a syntax error? No. It would cause a logic error, because sum and data could be initialized to any value.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *