Sum of the First N Natural Numbers

Sum of the First N Natural Numbers in C++

Learn to use accumulators and loops by building a program that calculates the total sum of all positive integers up to a number specified by the user.

Logic and Accumulation

The Accumulator Variable

We use a variable (usually named sum) initialized to 0. In each iteration of the loop, we add the current value of the counter to this variable.

Arithmetic Progression

While this can be solved with the formula $S = \frac{n(n+1)}{2}$, using a loop helps beginners understand how data changes state over time.

Step-by-Step Objective

  • Ask the user for a positive integer n.
  • Initialize an integer variable sum = 0.
  • Create a for loop that runs from 1 to n.
  • In each step, update the sum: sum += i.
  • Display the final accumulated value.

C++ Solution

sum_natural_numbers.cpp C++ Beginners
#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;

    cout << "Enter a positive integer: ";
    cin >> n;

    // Accumulate sum from 1 to n
    for (int i = 1; i <= n; i++) {
        sum += i; // Equivalent to sum = sum + i
    }

    cout << "The sum of the first " << n << " natural numbers is: " << sum << endl;

    return 0;
}

Console Output:

Enter a positive integer: 5
The sum of the first 5 natural numbers is: 15
Loop Logic & Variable State
For Loop Iteration Accumulator Patterns Compound Assignment Operators Loop Control Statements Arithmetic Accumulation Intermediate Logic Flow

Share this C++ Exercise

Help others learn about loops and accumulators in C++.

© C++ Programming Exercises. Master the art of performance coding.