Sum of First n Natural Numbers

Sum of First n Natural Numbers” is a very basic programming exercise problem for beginners. Here, we are given a number ‘n’ and our task is to compute the sum of first ‘n’ natural numbers.

Natural Numbers: 1,2,3,………

Example:

INPUT:
N = 5
OUTPUT:
15
Explanation:
1+2+3+4+5 = 15

There are two methods to compute the sum of first ‘n’ natural numbers:

  1. Using loop
  2. Using formula

METHOD 1: Using loop

This method computes the sum of first ‘n’ natural numbers in O(n).

C++ Program to compute sum of first ‘n’ natural numbers is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    //Scanning the number 'n'  
    int n;  
    cout<<"Enter the number 'n' : ";  
    cin>>n;  
      
    //Computing the sum of first 'n' natural numbers  
    int sum = 0;  
    for(int i = 1; i <= n;i++)  
    {  
        sum = sum + i;  
    }  
      
    //Printing the sum of first 'n' natural numbers  
    cout<<"Sum of first "<<n<<" natural numbers is "<<sum;  
}  

OUTPUT:
Enter the number 'n' : 5
Sum of first 5 natural numbers is 15

METHOD 2: Using formula

Sum of first ‘n’ natural numbers: n*(n+1)/2.

This method computes the sum of first ‘n’ natural numbers in O(1).

C++ Program to compute sum of first ‘n’ natural numbers is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    //Scanning the number 'n'  
    int n;  
    cout<<"Enter the number 'n' : ";  
    cin>>n;  
      
    //Computing the sum of first 'n' natural numbers  
    int sum = n*(n+1)/2;  
      
    //Printing the sum of first 'n' natural numbers  
    cout<<"Sum of first "<<n<<" natural numbers is "<<sum;  
} 
OUTPUT:
Enter the number 'n' : 5
Sum of first 5 natural numbers is 15

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *