# 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**:

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

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

- Using loop
- 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; }

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

**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; }

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