Program to calculate the series (1) + (1+2) + (1+2+3) + … + (1+2+3+4+…+n) in C++
Written by
C++ Program to calculate the series (1) + (1+2) + (1+2+3) + (1+2+3+4) + … + (1+2+3+4+…+n)
Given: The value of n is input from user and we find the sum of the series where i-th term is sum of first i natural numbers.
Example:
Input : n = 6
Output :
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
The sum of the above series is : 56
# Algorithm
- Take input
n
from the user. - Start a loop from
i = 1
toi <= n
. - Inside the loop, calculate the sum for the
i
th term by adding all the numbers from 1 toi
. - After the loop, print the total sum as the result.
Code:
#include <iostream>
using namespace std;
int main() {
int i, j, n, sum, total = 0;
cout << "Enter the value for nth term: ";
cin >> n;
for (i = 1; i <= n; i++) {
sum = 0;
for (j = 1; j <= i; j++) {
total += j;
sum += j;
cout << j;
if (j < i) {
cout << "+";
}
}
cout << " = " << sum << endl;
}
cout << "\nThe sum of the above series is: " << total << endl;
}
Output
Enter the value for nth term: 5
1 = 1
1+2 = 3
1+2+3 = 6
1+2+3+4 = 10
1+2+3+4+5 = 15
The sum of the above series is: 35