The do while loop is similar to the while loop. The primary difference is that with a do while loop the condition is tested at the bottom of the loop, unlike a while loop where the condition is tested at the top. This means that a do while loop will always execute at least once, whereas a while loop may never execute at all if its condition is false at the outset.
The syntax of a do while loop is
do { statement(s); } while (condition);
The do keyword starts the loop. The statement or statements belonging to the loop are enclosed in curly braces. After the close curly brace , the while keyword appears, followed by the condition in parentheses, terminated by a semicolon.
The following program is a modification of the one earlier in this chapter that used a while loop to continue to prompt the user to enter a positive number until the user either did so or quit, and then either outputted the positive number or a message that the user did not enter a positive number. This modification uses a do while loop instead of a while loop.
#include <iostream> using namespace std; int main(void) { int num; char choice; bool quit = false; do { cout << "Enter a positive number: "; cin >> num; if (num <= 0) { cout << "Number must be positive; try again (Y/N): "; cin >> choice; if (choice != 'Y') quit = true; } } while (num <= 0 && quit == false); if (quit == false) cout << "The number you entered is " << num << " "; else cout << "You did not enter a positive number"; return 0; }
The following are sample inputs and outputs. The first one has the user successfully enter a positive number the first time.
Enter a positive number: 4 The number you entered is 4
The next sample input and output has the user enter a positive number after two unsuccessful tries .
Enter a positive number: 0 Number must be positive; try again (Y/N): Y Enter a positive number: -1 Number must be positive; try again (Y/N): Y Enter a positive number: 4 The number you entered is 4
The final sample input and output has the user quit after two unsuccessful tries.
Enter a positive number: 0 Number must be positive; try again (Y/N): Y Enter a positive number: -1 Number must be positive; try again (Y/N): N You did not enter a positive number
The preceding program, which used the do while loop, did not need to prompt the user both before and inside the loop to enter a number as did the corresponding program that used the while loop. However, this program using the do while loop repeats the num < = 0 condition inside the loop, whereas the corresponding program that used the while loop did not need to do that.
As a general rule, I prefer a do while loop over a while loop in those situations in which the loop must execute at least once before a condition may be tested, simply because under these circumstances it seems illogical to test the condition prematurely on the first iteration of the loop. As you may recall, in the program variation that used the while loop, the value of quit could be true in the loop condition under either of two possibilities, one being it was the users first attempt to enter data so the user has not yet been asked whether they want to quit, and the other being it was the users second or later attempt to enter data and the user answered that they wanted to quit. By contrast, using the do while loop eliminates the first possibility.
The preceding program, in which the user had to enter a number, whether that number is positive or not, is an example of the situation in which the loop must execute at least once before a condition may be tested. Another common example of this situation is when a menu is displayed. Assume the program displays a menu such as the following:
Menu ==== 1. Add an entry 2. Edit an entry 3. Delete an entry 4. Exit
If the user chooses options 1, 2, or 3, the program performs the indicated operation (add, edit, or delete) and then again displays the menu for the users next choice. If the user chooses option 4, the program ends.
In this menu example, the menu always displays at least once; the user cannot choose to exit before being given that choice. Accordingly, a do while loop normally is preferable to a while loop when choosing a loop to display a menu.
With a do while loop, it is important that a variable used in the condition following the while keyword not be declared inside the loop.
In the program that demonstrated the do while loop, the variables num and quit were declared before the loop:
int num; char choice; bool quit = false; do { // statements } while (num <= 0 && quit == false);
These variables could not be declared inside the do while loop, as in the following code excerpt, because the code would not compile. The parentheses following the while keyword is highlighted, and the compiler error is that num and quit are undeclared identifiers.
char choice; do { int num; bool quit = false; // more statements } while (num <= 0 && quit == false);
The reason why this alternative will not compile concerns variable scope.
As you know from Chapter 3, a variable must be declared before it can be referred to in code. Once a variable is declared, it may be referred to wherever in the code it has scope.
Thus far, variables have been declared in main, just after the open curly brace which begins the body of the main function. This gives these variables scope until the close curly brace, which ends the body of the main function. Since thus far our programs have had only one function, main, as a practical matter, the variables, once declared, could be referred to throughout the entire program.
In this example, however, the variables num and quit are declared after the open curly brace that begins the body of the do while loop. That means their scope is limited to the area between that open curly brace and the close curly brace that ends the body of the do while loop. This area between an open and close curly brace also is referred to as a block.
The while keyword and the parentheses that follow it are outside the body of the do while loop, or put another way, after the close curly brace that ends the body of the do while loop. Since the variables num and quit were declared within the body of the do while loop, they do not have scope outside the body of the loop where the while parentheses are located. Therefore, these variables are regarded as undeclared when referred to within those parentheses.
This issue arises far more often with the do while loop than with the for or while loops. With for or while loops , the condition precedes the body of the loop, so any variables used in the condition necessarily would be declared before the loop or, in the case of the for loop, within the parentheses following the for keyword. By contrast, since the condition of a do while loop comes after the body of the loop, it is an easy mistake to declare the variables used in the condition before it, in the body of the loop.
This is our first discussion of the variable scope issue. However, it is by no means our last. This issue is not limited to the do while loop. It arises frequently when we start adding other functions to our programs, as we will do in upcoming chapters.