RUN


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 <= 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;

}

Report Error/ Suggestion

Related Posts:

[yuzo_views]



Interview Questions



CopyRight © 2020

CopyRight © 2020