C++ Program to Calculate Sum of Natural Numbers

C++ProgrammingServer Side Programming

The natural numbers are the positive integers starting from 1.

The sequence of natural numbers is −

1, 2, 3, 4, 5, 6, 7, 8, 9, 10……

Sum of the first n natural numbers can be calculated using the for loop or the formula.

Programs specifying both of these methods are given as follows −

Sum of Natural Numbers Using for loop.

The program to calculate the sum of n natural numbers using for loop is given as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int n=5, sum=0, i;
   for(i=1;i<=n;i++)
   sum=sum+i;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}

Output

Sum of first 5 natural numbers is 15

In the above program, a for loop is run from 1 to n. In each iteration of the loop, the value of i is added to the sum. So, the sum of the first n natural numbers is obtained. This is demonstrated by the following code snippet.

for(i=1;i<=n;i++)
sum=sum+i;

Sum of Natural Numbers using Formula

The formula to find the sum of first n natural numbers is as follows.

sum = n(n+1)/2

The program to calculate the sum of n natural numbers using the above formula is given as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int n=5, sum;
   sum = n*(n+1)/2;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}

Output

Sum of first 5 natural numbers is 15

In the above program, the sum of the first n natural numbers is calculated using the formula. Then this value is displayed. This is demonstrated by the following code snippet.

sum = n*(n+1)/2;
cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
raja
Published on 26-Sep-2018 14:19:34
Advertisements