The do-while-Loop
-
The syntax of the do-while-loop is:
do
Yes_Statement
while (Boolean_Expression);
As usual the single Yes_Statement can always be replaced by a compound statement (a group of statements enclosed by curely braces).
The execution sequence of the do-while-loop is as follows:
-
First the statement in the loop body is executed
-
The Boolean_expression is then evaluated. If it is true then the loop is executed again; the Boolean expression is checked again, and so forth.
-
When the Boolean_expression is tested and found to be false, the do-while-loop is exited and the next program statement after the while-loop is executed.
-
Note that the loop body is executed at least once even if the Boolean_expression evaluates to false when the
do-while-loop begin.
-
// Illustration of the use of the do-while-loop.
// The user is asked to enter two numbers of type double.
// The program then computes and prints out the answer for the
// product of the numbers.
// The user is then asked if (s)he wants the program to do another
// calculation.
// The user answers "yes" by typing the letter y in upper or lower case.
// and the process of asking to input two numbers and computing and
// printing out the product is repeated until the user responds by
// typing any key other than the letter y.
#include <iostream>
using namespace std;
int main ( )
{
double Num1, Num2, Product;
char Key;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(7);
do
{
cout << "Enter two numbers of type double: ";
cin>> Num1 >> Num2;
Product = Num1 * Num2;
cout << "The product of " << Num1 << " and " << Num2
<< " is: " << Product << endl << endl;
cout << "If you want me to calculate another product for you\n"
<< "then press \'Y\' or \'y\',\n"
<< "otherwise press any other key to end the calculation.\n";
cin >> Key;
} while (Key == 'Y' || Key == 'y');
cout << "It is always so nice working with you. Bye! \n\n";
return 0;
} //end main
A possible dialogue is:
Enter two numbers of type double: -2.13 3.1415962
The product of -2.13 and 3.1415962 is:
-6.6915999
If you want me to calculate another product for you
then press 'Y' or 'y'
otherwise press any other key to end the calculation.
y
Enter two numbers of type double: 1.2345678 8.7654321e-1
The product of 1.2345678 and 0.8765432 is:
1.0821520
If you want me to calculate another product for you
then press 'Y' or 'y'
otherwise press any other key to end the calculation.
n
It is always so nice working with you. Bye!
-
The do-while-loop is often used to verify that the input data from the keyboard are of the correct form. The following code illustrates how that can be done:
char ch;
do
{
cout << "Enter a digit: ";
cin >> ch;
} while ((ch < '0') || ('9' < ch));
The loop never ends until the user supplies the correct data.
-
If the loop condition turns out to be always satisfied, the loop will never end. Be careful not to have these so called infinite loops.
-
Note that the do-while loop ends with a semicolon.