The do while loop is the 2'nd type of loop, the main positive aspect of thios loop that whether the condition is true or false the loop will run one time, if the condition will be true then the loop will be continued otherwise it will stop..
The syntax of the do while statement is as follows:-
Code:
do
{
}
while(
Here the condition is at the last so the loop will run 1'st time till reaching the condition....
The followind point should be remembered while using do-while loop:---
1. (1)It is executed at least once..
2. (1)It is executed till the condition remains trueand the control comes out as soon as the loop ends.
3. (1)There must be some looping terminating condition otherwise the loop willnot stop...
Here are some e.g. To clear ur doubts........
* To check whether the number is Armstrong or not....
Note:- An armstrong no. Is a no. Whose digit cube sum is equal to the same no..
Code:
void main()
{
clrscr();
int n,k,r.s;
cout<<"Enter the number\n";
cin>>n;
k=n;
s=0;
do
{
r=n%10;
s=s+r*r*r;
n=n/10;
}while(n!=0);
if(k==s)
cout<<"It is Armstrong no.";
else
cout<<"It is not Armstrong No..";
getch();
}
In the above program I had taken 4 variables n for storing the number, k for storing the value of n so that we can check the condition,s for adding,r for taking remainder or storing every digit of the entered number...
So suppose u had entered the no 153 the no. Gets stored in k so n and k both will hold 153. Now the loop will begins first acc/cond given no will get divided be 10 and the remainder will get stored in r. First when u will divide 153 by 10 the remainder will come 3 the in second line cube of 3 i.e 27 will be added to s i.e 0 so s is now 27 then the remaining part will again got divided and the cube of 5 i.e 125 then again the last no cube i.e 1 will be added so the sum of 27+125+1=153 so the no. Is armstrong no..
* To find factorial of any number.
Code:
void main()
{
clrscr();
int n,f;
cout<<"Enter the number\n";
cin>>n;
f=1;
do
{
f=f*n;
n=n-1;
}while(n!=0);
getch();
}
I have already explained it so its should be clear to all...
No comments:
Post a Comment