In this tutorial, you will learn how to write a C++ Program to find the sum of natural numbers using formula, or a loop statement.
C++ Sum of Natural Numbers
To find the sum of first n natural numbers in C++, we can use the for loop to iterate from 1
to n
and accumulate the sum, or we can also use the formula n(n+1)/2
directly.
In this tutorial, we will write C++ Programs to find the sum of natural numbers, with the two methods mentioned above.
Programs
1. Compute sum of natural numbers using For loop
In the following program, we read a number into n
, and find the sum of natural numbers from 1 to n, using For Loop.
main.cpp
#include <iostream> using namespace std; int main() { int n; cout << "Enter a number : "; cin >> n; int sum = 0; for(int i = 1; i <= n; i++) { sum += i; } cout << "Sum : " << sum << endl; }
Output
Enter a number : 5 Sum : 15 Program ended with exit code: 0
Enter a number : 1256 Sum : 789396 Program ended with exit code: 0
2. Compute sum of natural numbers using formula
In the following program, we read a number into n
, and find the sum of natural numbers from 1 to n, using the formula n(n+1)/2
.
main.cpp
#include <iostream> using namespace std; int main() { int n; cout << "Enter a number : "; cin >> n; int sum = n * (n + 1) / 2; cout << "Sum : " << sum << endl; }
Output
Enter a number : 5 Sum : 15 Program ended with exit code: 0
Enter a number : 1256 Sum : 789396 Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to find the sum of first n Natural Numbers.