next up previous
Next: Activity Up: while Loop Previous: while Loop

do-while Loop

Unlike the for and the while loops, in which the condition is tested at the top of the loop, the do while loop checks its condition at the bottom of the loop. This means that the do while loop while always execute at least once. The general form of the do while loop is:

do{
statements; }
while{condition};

Example
#include <iostream.h>
main()
{
int num;
do {
cout << "Enter a number";
cin >> num;
} while(num !=100);
return 0;
}

Example
#include <iostream.h>
#include <stdlib.h>
main()
{
int hope;
int guess;
hope=rand();
do{
cout <<"Enter your guess:";
cin >> guess;
if(guess==hope){
cout << "You got it";
cout << hope << "is the magic number $\backslash$n";
}
else {
cout <<" Sorry";
if(guess>hope)
cout << "Your guess is too high $\backslash$n";
else cout<< "Your guess is too low $\backslash$n";
}
} while(guess !=hope);
return 0;
}



Yousef Haik
2/23/1998