Wednesday, 29 April 2015

Write a Program in C++ to Print first n natural numbers and their sum using do-while loop.

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:-

                      

3 comments: