Sum of n Natural Numbers

Program to calculate sum of first n natural numbers

BeginnerTopic: Loop Programs
Back

C++ Sum of n Natural Numbers Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#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

Understanding Sum of n Natural Numbers

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.

---

1. 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

---

2. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

3. Declaring and Initializing Variables

int n, sum = 0;

Variable `n`:

Stores the number entered by the user
This is the upper limit (we'll sum from 1 to n)

Variable `sum`:

Stores the accumulated sum

-

Initialized to 0

This is crucial!

Why initialize sum to 0?

We need a starting point for addition
If sum is not initialized, it contains garbage value (random number)
Starting with 0 ensures: 0 + 1 + 2 + 3 + ... = correct result

What happens if we don't initialize?

sum might contain a random value like 12345
Then: 12345 + 1 + 2 + 3 + ... = wrong answer!

---

4. Taking Input From User

`cout << "Enter a positive integer: ";`

cin >> n;

Prompts user to enter a number
Reads and stores it in n

Example:

User enters:

10

n = 10

---

5. Understanding the For Loop

for (int i = 1; i <= n; i++)

Loop structure:

-

Initialization:

int i = 1 → Start from 1

-

Condition:

i <= n → Continue while i is less than or equal to n

-

Increment:

i++ → Increase i by 1 after each iteration

How it works:

-

Iteration 1:

i = 1, check 1 <= 10

true

→ execute

-

Iteration 2:

i = 2, check 2 <= 10

true

→ execute

-

Iteration 3:

i = 3, check 3 <= 10

true

→ execute

...

-

Iteration 10:

i = 10, check 10 <= 10

true

→ execute

-

Iteration 11:

i = 11, check 11 <= 10

false

stop

---

6. Accumulation Pattern - Building the Sum

sum += i;

This is the

accumulation pattern

the core of this program.

What `sum += i` means:

It's shorthand for: sum = sum + i
Takes current value of sum
Adds i to it
Stores the result back in sum

Step-by-step execution (with n = 10):

Before loop:

sum = 0

Iteration 1 (i = 1):

sum = sum + isum = 0 + 1 = 1
Now: sum = 1

Iteration 2 (i = 2):

sum = sum + isum = 1 + 2 = 3
Now: sum = 3

Iteration 3 (i = 3):

sum = sum + isum = 3 + 3 = 6
Now: sum = 6

Iteration 4 (i = 4):

sum = 6 + 4 = 10

Iteration 5 (i = 5):

sum = 10 + 5 = 15

Iteration 6 (i = 6):

sum = 15 + 6 = 21

Iteration 7 (i = 7):

sum = 21 + 7 = 28

Iteration 8 (i = 8):

sum = 28 + 8 = 36

Iteration 9 (i = 9):

sum = 36 + 9 = 45

Iteration 10 (i = 10):

sum = 45 + 10 = 55

After loop:

sum = 55

---

7. Visual Representation

Think of sum as a container that accumulates values:

Initial: sum = 0 (empty container)
Iteration 1: sum = 0 + 1 = 1 [1]
Iteration 2: sum = 1 + 2 = 3 [1, 2]
Iteration 3: sum = 3 + 3 = 6 [1, 2, 3]
Iteration 4: sum = 6 + 4 = 10 [1, 2, 3, 4]

...

Iteration 10: sum = 45 + 10 = 55 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

---

8. Displaying the Result

cout << "Sum of first " << n << " natural numbers = " << sum << endl;

This prints:

Text: "Sum of first "
Value of n: 10
Text: " natural numbers = "
Value of sum: 55
New line

Output:

Sum of first 10 natural numbers = 55

---

9. Mathematical Formula (Alternative Method)

There's a mathematical formula for this:

Sum = n × (n + 1) / 2

For n = 10:

Sum = 10 × (10 + 1) / 2
Sum = 10 × 11 / 2
Sum = 110 / 2
Sum =

55

Why use a loop instead of formula?

Loops teach programming concepts
Formula only works for this specific problem
Loops are more flexible and applicable to many problems
Understanding loops helps solve complex problems

---

10. Edge Cases to Consider

What if user enters 0?

Loop condition: i <= 01 <= 0 is

false

Loop doesn't execute
sum remains 0
Output: "Sum of first 0 natural numbers = 0" ✅ (correct)

What if user enters 1?

Loop executes once: i = 1
sum = 0 + 1 = 1
Output: "Sum of first 1 natural numbers = 1" ✅ (correct)

What if user enters negative number?

Program doesn't check for this
Loop might not execute (if n < 1)
Could add validation: if (n < 1) { cout << "Invalid input"; return 0; }

---

Summary

Initialize sum to 0 before the loop (crucial!)
Use for loop to iterate from 1 to n
Accumulation pattern: sum += i builds up the total
This pattern is used in many programs: finding totals, averages, maximums, etc.
Understanding accumulation is essential for solving many programming problems

This program teaches the

accumulation pattern

, which is one of the most important patterns in programming. You'll use this concept when:

Calculating totals (sum of array elements)
Finding averages
Counting occurrences
Building strings or lists
Many other real-world applications

Mastering this pattern opens the door to solving complex problems efficiently.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Sum of n Natural Numbers

This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents