Calculating the Sum of Natural Numbers in C++

The Problem Statement

Natural numbers, also known as positive integers, are the building blocks of mathematics. Imagine you’re asked to write a program that calculates the sum of natural numbers up to a given positive integer, say n. For instance, if the user enters 5, the program should display the result of 1 + 2 + 3 + 4 + 5.

The Solution

Our C++ program tackles this problem using a straightforward approach. It utilizes a for loop to iterate from 1 to the user-inputted number, adding each natural number to the sum.


#include <iostream>

using namespace std;

int main() {
    int n, sum = 0;
    cout << "Enter a positive integer: ";
    cin >> n;
    if (n <= 0) {
        cout << "Sum = 0" << endl;
        return 0;
    }
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    cout << "Sum of natural numbers up to " << n << " is " << sum << endl;
    return 0;
}

How it Works

Let’s break down the code step by step:

  • We prompt the user to enter a positive integer.
  • If the user enters a negative number or zero, we display Sum = 0 and terminate the program.
  • for loop to iterate from 1 to the user-inputted number, adding each natural number to the sum variable.
  • Finally, we display the calculated sum.

Beyond Loops: Recursion

While our program uses a for loop to calculate the sum of natural numbers, there’s another approach worth exploring: recursion. If you’re interested in learning how to calculate the sum of natural numbers using recursion, be sure to check out our companion article.

By mastering this fundamental C++ program, you’ll gain a deeper understanding of how to tackle real-world problems. So, get coding and start calculating those natural numbers!

Leave a Reply