- Related Questions & Answers
- Java Program to calculate Sum of squares of first n natural numbers
- PHP program to calculate the sum of square of first n natural numbers
- C++ program to Find Sum of Natural Numbers using Recursion
- Sum of first n natural numbers in C Program
- Program to find sum of first n natural numbers in C++
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Sum of sum of first n natural numbers in C++
- Java program to find the sum of n natural numbers
- Java Program to cube sum of first n natural numbers
- C Program for the cube sum of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- 8085 program to find the sum of first n natural numbers

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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

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

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;

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.

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

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;

Advertisements