Sum of n Natural Numbers in C++

Sum 1..n in C++. n=10 is 55. Initialize sum to 0. Or use n*(n+1)/2.

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}

Output

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

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.