Next: Example Program: Student Mark
Up: The do-while statement
Previous: Example Program: Sum of
The do-while statement is useful for checking that input from a
user lies in a valid range and repeatedly requesting input until it is
within range. This is illustrated in the following portion of C++
program:
bool accept; // indicates if value in range
float x; // value entered
float low, high; // bounds for x
// assume low and high have suitable values
do {
cout << "Enter a value (" << low <<" to "
<< high << "):";
cin >> x;
if (low <= x && x <= high)
accept = true;
else
accept = false;
}
while (!accept);
Download program.
Note the use of the logical operator not (!) operating on the
boolean value, to invert its truth value.
Another way of controlling the loop is to assign the value of the
condition directly to accept. At first sight, this may appear
strange, but the condition is already being evaluated as either
true or false, so it makes sense to replace the
if-else statement with
accept = low <= x && x <= high;