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

Related Posts:

  1. Program to Reverse a Number.
  2. Program to swap two Numbers.
  3. Program to print Fibonacci Series up to Nth Term.
  4. Program to find and print nth Fibonacci number.
  5. Program to find Power of the Number.
  6. Program to find Quotient and Remainder.
  7. Program to find largest amongst three numbers.
  8. Program to find factorial of a number.
  9. Program to find GCD of two numbers.
  10. Program to find LCM of two numbers.
  11. Program to check whether entered number is odd or even.
  12. Program to check whether entered number is prime number or not.
  13. Program to check whether entered number is palindrome or not.
  14. Program to check whether entered number is Armstrong Number or Not.
  15. Program to convert binary number to octal number.
  16. Program to convert binary number to decimal number.
  17. Program to convert binary number to hexadecimal number.
  18. Program to convert octal number to binary number.
  19. Program to convert octal number to decimal number.
  20. Program to convert octal number to hexadecimal number.

You may also like...

Leave a Reply

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