Wednesday, 29 April 2015

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

Program using for loop:- 

Syntax of for loop:-      
                                   for(initialization; test expression; re-initialization)
                                     {
                                        body of the loop
                                   
                                            }

Initialization Expression:- It is executed only once when the loop first starts.It provide an initial value for the local variable.

Test Expression:- It is executed every time through the loop before the body of the loop is executed. Mean it tell about the end value. There we will use relational operators. If the test expression is true, the body of the loop is executed, and if false, the control comes out of the loop.

Increment/Decrement (re-initialization) Expression:-It is always at the end of the loop, after the body of the loop.

Let us take an example:-

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

                   
                    #include<iostream.h>


 void main()
 {
 int n,i,sum=0;
cout<<"enter the value of n";
cin>>n;
cout<<"\n first "<<n<<"natural numbers are";

for(i=1;i<=n;i++)

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

 sum=sum+i;




}

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


 }

Output:- 

  

No comments:

Post a Comment