Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of the series 1 / 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + upto n terms in C++
In this article, we are given an integer n. It defines the number of terms in the series: 1/1 + ( (1+2)/(1*2) ) + ( (1+2+3)/(1*2*3) ) + ? + up to n terms. Our task is to write a program to calculate the sum of series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ? up to n terms.
The above series can be represented as: $$ \sum_{k=1}^{n} \frac{\sum_{j=1}^{k} j}{k!} $$
Scenario
The following example calculates the sum for the given series up to 4 terms:
<strong>Input:</strong> n = 4 <strong>Output:</strong> 3.916 <strong>Explanation</strong> n = 4 Series: 1/1 + ((1+2)/(1*2)) + ((1+2+3)/(1*2*3)) + ((1+2+3+4)/(1*2*3*4)) = 1 + 1.5 + 1 + 0.416 = 3.916
C++ Program to Calculate Sum of Series
To calculate the sum of the given series 1/1 + ( (1+2)/(1*2) ) + ( (1+2+3)/(1*2*3) ), we iterate through the for loop and calculate the value of sum and product up to the current index. The sum here is the cumulative sum, and the product is the factorial of i. For each element i, we divide the sum and product and add the result to calculate the total sum.
Example
Here is the code example to calculate the sum of the given series:
#include <iostream>
using namespace std;
double sumProduct(int n)
{
double result = 0.0;
int sum = 0, product = 1;
for (int i = 1; i <= n; i++){
sum += i;
product *= i;
result += ((double)sum / product);
}
return result;
}
int main()
{
int n = 6;
cout << "Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... up to "
<< n << " terms is: " << sumProduct(n);
return 0;
}
The output of the above code is as follows:
Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... up to 6 terms is: 4.07083
The detailed explanation of the above program is as follows:
Let n = 3, sum = 0, product = 1 and result = 0
for i = 1
=> sum += 0+1 = 1, product *= 1*1, = 1
result += 0 +(1/1) = 1
for i = 2
=> sum += 1+2 = 3, product *= 1*2 = 2
result = 1 + (3/2) = 2.5
for i = 3
=> sum += 3+3 = 6, product *= 2*3 = 6
result = 2.5 + (6/6) = 3.5
<strong>Output: 3.5</strong>
