Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Sum of n Natural Numbers in C++

Add the numbers 1 to n in C++ with a for loop and a running total. Compare the loop with the n(n+1)/2 formula and see what happens for n = 0 or a huge n.

BeginnerLoop ProgramsExample 2 of 14
sum-of-n-natural-numbers.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int n, sum = 0;
6
7 cout << "Enter a positive integer: ";
8 cin >> n;
9
10 for (int i = 1; i <= n; i++) {
11 sum += i;
12 }
13
14 cout << "Sum of first " << n << " natural numbers = " << sum << endl;
15
16 return 0;
17}

Sample Output

Sum of first 10 natural numbers = 55

1 + 2 + ... + 10.

In this one

  • How a running total (accumulator) works
  • Why sum must start at 0
  • How the loop result matches n(n+1)/2
  • When the total overflows int

How it works

  1. 1

    sum starts at 0; read n (10).

  2. 2

    Each pass adds i to sum: 1, 3, 6, 10 ...

  3. 3

    After i = 10, sum is 55.

  4. 4

    The loop ends and the total prints.

Edge cases

Uninitialized sum

Write int n, sum; without = 0.

sum starts with garbage, so the total is wrong. Accumulators must be set before the loop.

n = 0 or negative

Enter 0 or -4.

i <= n is false at the start, so the loop never runs and the sum prints as 0.

What's going on

Sum of the first n natural numbers: 1 + 2 + … + n. For n = 10 that's 55.

int n, sum = 0;

sum starts at 0. Uninitialized sum plus 1+2+… is a random number plus 55.

cin >> n;

Sample: 10.

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

sum += i; meaning sum = sum + i.

Walk 10: 0→1→3→6→10→15→21→28→36→45→55.

n = 0: loop never runs, sum stays 0. n = 1: one iteration, sum is 1. Negative n: i <= n is already false at i = 1, so you print 0. The program does not scold you.

Closed form: n * (n + 1) / 2. Same 55. Integer division: compute n * (n + 1) / 2 not n / 2 * (n + 1) if n is odd — 10 works either way, 9 does not (9/2 is 4). The loop avoids that trap.

int overflow: n around 65536 and the triangular number no longer fits. long long if the homework goes that high.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the sum of 1 to 6?

Pick an answer to check it.

Question 2

Why must sum be set to 0 first?

Pick an answer to check it.

Questions people ask

Is the formula better than the loop?

n * (n + 1) / 2 takes one step instead of n steps. The loop is useful because the same shape works for sums that have no simple formula.

What does sum += i mean?

It is short for sum = sum + i.

How do I sum only even numbers?

Start at 2 and use i += 2, or keep i++ and add only when i % 2 == 0.