do-while
statement is this:
do
{
// statements
}
while (Boolean_Expression);
The do-while
statement is a looping
statement. It tests the Boolean expression at the end of the loop. A
statement (or a sequence of statements) is executed while an expression is
true. The do-while
statement differs from
the while
statement in one major respect: the body of the loop is always
executed at least once
in the do-while
statement.
For example, the following loop reads marks until a valid mark is entered.
This do-while
loop is
event-controlled.
do
{
cout << "Please enter a mark: ";
cin >> mark;
if (mark < 0 || mark > 100)
cout << "Invalid mark. Try again. " << endl << endl;
}while (mark < 0 || mark > 100);
The following C++ code shows a count-controlled
do-while
statement:
sum = 0;
counter = 0;
do
{
cout << "Please enter a mark: ";
cin >> mark;
sum = sum + mark;
counter++;
} while (counter < 10);
cout << "The average of the marks entered is " << sum/counter << endl;
©Department of Computer Science, University of Regina.