One interesting thing about the while loop is that if the loop condition is false, the while loop may not execute at all. It is sometimes the case that we want a loop to execute at least once, such as when displaying a menu. To facilitate this, C++ offers the do while loop:
do statement; while (condition);
The statement in a do while loop always executes at least once. After the statement has been executed, the do while loop checks the condition. If the condition is true, the CPU jumps back to the top of the do while loop and executes it again.
Here is an example of using a do while loop to display a menu to the user and wait for the user to make a valid choice:
using namespace std;
// nSelection must be declared outside do/while loop
cout << "Please make a selection: " << endl;
cout << "1) Addition" << endl;
cout << "2) Subtraction" << endl;
cout << "3) Multiplication" << endl;
cout << "4) Division" << endl;
cin >> nSelection;
} while (nSelection != 1 && nSelection != 2 &&
nSelection != 3 && nSelection != 4);
// do something with nSelection here
// such as a switch statement
One interesting thing about the above example is that the nSelection variable must be declared outside of the do block. Think about it for a moment and see if you can figure out why that is.
If the nSelection variable is declared inside the do block, it will be destroyed when the do block terminates, which happens before the while conditional is executed. But we need the variable to use in the while conditional -- consequently, the nSelection variable must be declared outside the do block.
Generally it is good form to use a do while loop instead of a while loop when you intentionally want the loop to execute at least once, as it makes this assumption explicit -- however, it’s not that big of a deal either way.
|5.7 -- For statements|
|5.5 -- While statements|