In this example, you’ll learn to calculate the sum of natural numbers.
To understand this Program to Calculate Sum of Natural Numbers, you should have the knowledge of following C++ programming topics:
- C++ for Loop
Positive integers 1, 2, 3, 4… are known as natural numbers.
This program takes a positive integer from the user( suppose the user entered n ) then, this program displays the value of 1+2+3+….+n.
Program to find Sum of Natural Number using loop
#include <iostream> using namespace std; int main() { int n, sum = 0; cout << "Enter a positive integer: "; cin >> n; for (int i = 1; i <= n; ++i) { sum += i; } cout << "Sum = " << sum; return 0; }
Output
Enter a positive integer: 50 Sum = 1275
This program assumes that user always enters the positive number.
If the user enters the negative number, Sum = 0 is displayed and the program is terminated.
This program can also be done using recursion. Check out this article for calculating the sum of natural numbers using recursion.
Related Program
- C++ Program to check leap year.
- C++ Program to find factorial.
- C++ Program to generate Multiplication table.
- C++ Program to display Fibonacci series.
- C++ Program to find GCD using for and while loop.
- C++ Program to find LCM.
- C++ Program to reverse integer or number.
- C++ Program to display factors of a Number.
Ask your questions and clarify your/others doubts on Sum of Natural Number by commenting. Documentation