Wednesday, 29 April 2015

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

Program using while Loop:-
                                               Syntax of while Loop:-
               
               while(condition)
              {

                      body of loop
               }
       
 The following points should be remembered while using while loop:-

- It may not be executed even once if the condition is False initially.
- 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 to Print first n Natural numbers and their sum using 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";

while(i<=n)

{
cout<<"\n"<<i<<"  ";

 sum=sum+i;

 i++;


}

cout<<"\n the sum i ="<<sum;

                                            }


 Output :-

No comments:

Post a Comment