Program to calculate the series (1) + (1+2) + (1+2+3) + … + (1+2+3+4+…+n) in C++

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

  1. Take input n from the user.
  2. Start loops starting from 1 to n and calculate sum for each iteration.
  3. And print the total sum as output.

Code:

//C++ program to find the sum of the series (1)+(1+2)+(1+2+3)+(1+2+3+...+n)

#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 &lt;= i; j++)

{

  total += j;

  sum += j;

  cout &lt;&lt; j;

  if (j &lt; i)

  {

    cout &lt;&lt; "+";

  }

}

cout &lt;&lt; " = " &lt;&lt; sum &lt;&lt; endl;

}

cout << "\nThe sum of the above series is: " << total << endl;

}