C++ Program to Calculate Sum of Natural Numbers

To understand this example, you should have the knowledge of the following C++ programming topics:


Positive integers 1, 2, 3, 4... are known as natural numbers.

This program takes a positive integer from user (suppose user entered n ) then, this program displays the value of 1 + 2 + 3 + ... + n.


Example: Sum of Natural Numbers 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 positive number.

If user enters negative number, Sum = 0 is displayed and program is terminated.

This program can also be done using recursion. Check out this article for calculating sum of natural numbers using recursion.

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to calculate the sum of first n natural numbers.

  • Return the sum of first n natural numbers.
  • For example, if n is 5, the return value should be 15.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges