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.
Key Concepts Learned:
- Variable Initialization: Why starting at 0 is critical for sums.
- Compound Assignment: Using
+=to simplify your code. - Loop Control: Managing the range of a
forloop.
Course:
Introduction to C++
Step-by-Step Objective
- Ask the user for a positive integer
n. - Initialize an integer variable
sum = 0. - Create a
forloop that runs from 1 ton. - 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