Here are two examples,
Printing only even number
#include<iostream>
using namespace std;
int main()
{
int num,even=0;
cout<<"Enter Number of limit: ";
cin>>num;
// loop execute at least one time doesn't matter condition true or false
do
{
cout<<even<<" "; // print even value
even = even+2; // increment value by 2
}
while(even<num); // check condition
return 0;
}
OUTPUT
Enter Number of limit: 9
0 2 4 6 8
Explanation
In the program, we have declared two variables.
int number,even=0;
Where, the user has been asked for input for the variable number while the variable even has been initialized.
As we know that in do-while loop, the body-of-loop execution is first, then the updation takes place and in the last the condition will be checked. so here,
So here first, the value of variable even inside the body-of-loop will be printed which is 0
then up-dation will take place
even = i+2;
means,
even = i+2;
Now the value of variable even has become 2.
after this, in last condition will be checked outside the loop,
while(even<num);
means,
while(2<9);
Because here, the condition is going true, so the loop will execute again and the loop will continue to execute until the condition becomes false.
Meaning until the value of the variable even gets increased to 9, i.e. the value of the variable even will be 9, the loop will be terminated. such as,
2time
even = 2+2; // 4
while(2<9);// true
3rd tim
even = 4+2; // 6
while(4<9) //true
4th time
even = 6+2; // 8
while(6<9)//true
5th time
even = 8+2; // 10
while(10<9)// false
in 5th condition becoming false so loop will be terminate.
#include<iostream>
using namespace std;
int main()
{
int ch;
float num1,num2;
// creating menu wizard using do-while loop
do{
clrscr();
cout<<"Enter any two number: ";
cin>>num1>>num2;
cout<<"\nselection operation\n";
cout<<"1> Addition"<<endl;
cout<<"2> Substriction"<<endl;
cout<<"3> Multiply"<<endl;
cout<<"4> Division"<<endl;
cout<<"0> Exit"<<endl;
cout<<"Your choice:";
cin>>ch;
cout<<endl;
switch(ch)
{
case 1: cout<<"\nAddition are"<<endl;
cout<<num1<<"+"<<num2<<" = "<<num1+num2;
break;
case 2: cout<<"\nsubstriction are"<<endl;
cout<<num1<<"-"<<num2<<" = "<<num1-num2;
break;
case 3: cout<<"\nmultiply are"<<endl;
cout<<num1<<"x"<<num2<<" = "<<num1*num2;
break;
case 4: cout<<"\ndivision are"<<endl;
cout<<num1<<"/"<<num2<<" = "<<num1/num2;
break;
}
}while(ch!=0);
}
OUTPUT:-
Enter any two number: 12 13
selection operation
1> Addition
2> Substriction
3> Multiply
4> Division
0> Exit
Your choice:
multiply are
12x13 = 156
selection operation
1> Addition
2> Substriction
3> Multiply
4> Division
0> Exit
Your choice:0
Related exercise,
C++ Examples