What for and while commands have in common is the examination of condtion_of_execution before the program executes the command block. Therefore, it can happen that the command block isn’t executed not once. However, it is often necessary to perform one operation and that, depending on its outcome, possibly repeating this operation. For that cases we use the do-while loop and its syntax is given below.
While ( repeating_condition) ;
IMPORTANT – Repeating_condition in while loop must be closed with a semicolon sign (;). This rule can only be applied in the DO-WHILE BLOCK
We will illustrate the application of do-while block on a game in which you need to guess a random generated number. After each guess the program will give you information about the distance between your input number and the random number. Under distance we mean is your guesses number higher or lower than the random generated number.
Start a new project in the Microsoft Visual Studio or Dev C++ and wright the following code.
// Do-While loop.cpp : Defines the entry point for the console application.
using namespace std;
int _tmain(int argc, _TCHAR* argv)
long double r = 1000000000;
long double required_number = (rand());
cout << "You need to guess the number between 1 and "
<< r << endl;
long double my_number;
long double number_of_attempts = 0;
cout << ++number_of_attempts << ". attempt: ";
cin >> my_number;
if (my_number > required_number)
cout << "Less!"<< endl;
else if (my_number < required_number)
cout << "MORE!" << endl;
} while(my_number != required_number);
cout << "SUCCESS!" <<endl;
In this program for generating random number we have used the function rand( ) from header cstdlib. This function as a result returns a random number between 0 and RAND_MAX, and this number is also defined in the cstdlib library.
So as you see in this program we have to guess the random number. In program if we write a number which is bigger than random number the program will display message “Less.” If we write the number which is less than the random number the program will display message “MORE.” At the end when we guess the random number the program will display message “SUCCESS.” Enjoy your game.