Sum of n Natural Numbers

Program to calculate sum of first n natural numbers

C++Beginner
C++
#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 of first " << n << " natural numbers = " << sum << endl;
    
    return 0;
}

Output

Enter a positive integer: 10
Sum of first 10 natural numbers = 55

Sum of n Natural Numbers in C++

This program calculates the sum of the first n natural numbers. Natural numbers are positive integers starting from 1 (1, 2, 3, 4, 5, ...). This program demonstrates accumulation, which is a fundamental pattern in programming where we build up a result by repeatedly adding values.

What This Program Does

The program:

  • Takes a positive integer n as input
  • Calculates the sum: 1 + 2 + 3 + 4 + ... + n
  • Displays the result

Example:

  • If n = 10, it calculates: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = ## 55

This is a classic problem that teaches:

  • Loop iteration
  • Accumulation pattern (building up a sum)
  • Variable initialization

Understanding Accumulation

The key concept here is ## accumulation - we start with a sum of 0 and keep adding numbers to it.

cpp
int sum = 0;  // Initialize sum to 0
for (int i = 1; i <= n; i++) {
    sum += i;  // Add i to sum in each iteration
}

How it works:

  • Start with sum = 0
  • Iteration 1: sum = 0 + 1 = 1

  • Iteration 2: sum = 1 + 2 = 3

  • Iteration 3: sum = 3 + 3 = 6

  • Iteration 4: sum = 6 + 4 = 10

  • ...
  • Iteration n: sum = previous_sum + n

The += Operator

sum += i; is shorthand for sum = sum + i;

This operator:

  • Takes the current value of sum
  • Adds i to it
  • Stores the result back in sum

Alternative Formula

There's also a mathematical formula for this:

Sum = n × (n + 1) / 2

For n = 10:

  • Sum = 10 × 11 / 2 = 110 / 2 = 55

However, using a loop is more educational and demonstrates the accumulation pattern, which is used in many programming problems.

Summary

  • Natural numbers start from 1 (1, 2, 3, 4, ...)
  • Use a loop to iterate from 1 to n
  • Accumulate the sum using sum += i
  • This pattern is fundamental for many programming problems
  • Understanding accumulation helps in solving complex problems involving sums, products, and other aggregations

This program teaches:

  • Loop iteration
  • Accumulation pattern
  • Variable initialization
  • Building up results incrementally

Understanding this pattern is essential for:

  • Calculating sums, products, averages
  • Processing arrays and lists
  • Many algorithmic problems
  • Real-world data processing