Tuesday, 17 June 2014

C++ program to find the sum of first n natural numbers

Here are C++ programs to print and find the sum of first n natural numbers. First program simply finds sum of first n natural numbers, second program find the sum of first n natural numbers using recursion, third program find the sum of squares of first n natural numbers and fourth program find the sum of cubes of first n natural numbers.


C++ programs to print and find the sum of first n natural numbers
#include<iostream>
using namespace std;
int main()
{
    int n,sum=0;
    cout<<"Enter the number ";
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cout<<i<<"   ";
        sum+=i;
    }
    cout<<endl<<"Sum "<<sum;
    return 0;
}

OUTPUT




C++ program to find the sum of first n natural numbers using recursion
#include<iostream>
using namespace std;
int sumofn(int n,int sum)
{
    if(n==0)
        return sum;
    sumofn(n-1,sum+n);
}
int main()
{
    int n;
    cout<<"Enter the value of n : ";
    cin>>n;
    cout<<"Sum = "<<sumofn(n,0);
}

OUTPUT




C++ program to find the sum of squares of first n natural numbers
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int n,sum=0;
    cout<<"Enter the number ";
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        sum+=i*i;
    }
    cout<<"Sum = "<<sum;
    return 0;
}

OUTPUT




C++ program to find the sum of cubes of first n natural numbers
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int n,sum=0;
    cout<<"Enter the number ";
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        sum+=i*i*i;
    }
    cout<<"Sum = "<<sum;
    return 0;
}

OUTPUT

No comments:

Post a Comment