Program using do-while loop:-
Syntax of do-while loop:-
do
{
body of loop
} while(condition);
The following points should be remembered while using the do-while loop:
- It is executed at least once.
-It is executed till the condition remains true and the control comes out of the loop when the condition becomes false.
Let us take an example:-
Write a Program in C++ to Print first n natural numbers and their sum using do-while loop.
#include<iostream.h>
void main()
{
int n,i=1,sum=0;
cout<<"enter the value of n";
cin>>n;
cout<<"\n first "<<n<<"natural numbers are";
do
{
cout<<"\n"<<i<<" ";
sum=sum+i;
i++;
} while(i<=n);
cout<<"\n the sum i ="<<sum;
}
Output:-
Syntax of do-while loop:-
do
{
body of loop
} while(condition);
The following points should be remembered while using the do-while loop:
- It is executed at least once.
-It is executed till the condition remains true and the control comes out of the loop when the condition becomes false.
Let us take an example:-
Write a Program in C++ to Print first n natural numbers and their sum using do-while loop.
#include<iostream.h>
void main()
{
int n,i=1,sum=0;
cout<<"enter the value of n";
cin>>n;
cout<<"\n first "<<n<<"natural numbers are";
do
{
cout<<"\n"<<i<<" ";
sum=sum+i;
i++;
} while(i<=n);
cout<<"\n the sum i ="<<sum;
}
Output:-
Is it true that there is semi colon after while loop?
ReplyDeleteTell me fast
ReplyDeleteyes its true because end of the loop will be there, and we have to close it.
ReplyDelete