The do-while loop is similar to a while loop, only the conditional statement is only evaluated after the body has run at once. There are very few situations where a do-while loop is more natural than a while loop, however, one is where you prompt the user for input and quit when a certain value is reached.
Program 1 asks the user to enter a number and the program prints n! allowing the user to also enter 0 to quit.
Program 1. Printing the smallest factor.
#include <iostream> using namespace std; int main() { do { cout << "Enter a positive integer (0 to quit): " << endl; cin >> n; result = 1; for ( int i = 1; i <= n; ++i ) { result *= i; } cout << n << "! = " << result << endl; } while ( n != 0 ); // end of loop cout << "You entered a negative number. Bye." << endl; return 0; } |
Very seldom does a situation require a do-while loop; often the loop can be written as naturally using a while loop. If the do-while structure is necessary, you must document this.
The function in Program 2 uses Newton's method to find the square root of the argument. It starts by using the approximation x to the root and calculates the next approximation, halting if the two are equal.
Program 2. Finding the square root of a number.
double sqrt( double x ) { double current = 0.0; double next = x; // Perform at least one iteration of Newton's method before // comparing if the current value equals the next value. // // Note this is a simplification of Newton's method which // normally would look like // next = current - (current*current - x)/(2.0*current); do { current = next; next = 0.5*(current + x/current); } while ( next != current ); return current; } |
To write this as a while loop, you would have to either seed current with a value like ∞ or do something equally unnatural.
1. Write a do-while loop which continues to prompt the user for an integer between 1 and 10 and repeats the question if the user enters an integer less than 1 or greater than 10.
2. Write a do-while loop which prompts the user for a positive integer and repeats the question if the user enters a negative integer.
3. Write a do-while loop which continues to prompt the user to enter a character 'y' or 'n'. If the user enters any other character, prompt the user again.