Search This Blog

Wednesday, 24 October 2012

The following program find the sum of the first n natural numbers

#include<iostream.h>
int sum(int);
void main()
{
int n1,res;
cout<<"Enter a integer number:";
cin>>n1;
res=sum(n1);
cout<<"The sum of first"<<n1<<" numbers is "<<res;
}
int sum(int n2)
{
int i,sum;
sum=0;
for(i=1;0<=n2;i++)
sum+=i;
return sum;
}

Output:
Enter a integer number : 10
The sum of first 10 numbers is 35

No comments:

Post a Comment