Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two values x and n that corresponds to the given series. Our task is to create a program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++.

Problem description − we need to find the sum of series based on the given values of x and n. In the series, every other term differs from the previous term by x/i for ith term.

Let’s take an example to understand the problem

Input

x = 6, n = 4

Output

29.8

Explanation

The sum of the series is

1 + 6/2 + 36/6 + 216/24 + 1296/120 = 29.8

Solution Approach

To find the sum of the series, we will find the nth term by multiplying the previous term by the x/i. And find the sum by adding all terms.

Program to illustrate the solution

Example

 Live Demo

#include <iostream>
using namespace std;
float calcSeriesSum(int x, int n){
   float sumVal = 1, term = 1;
   for(float i = 2; i <= (n + 1) ; i++){
      term *= x/i;
      sumVal += term;
   }
   return sumVal;
}
int main(){
   int x = 6, n = 4;
   cout<<"The sum of the series is "<<calcSeriesSum(x, n);
   return 0;
}

Output

The sum of the series is 29.8
raja
Published on 27-May-2020 09:34:55
Advertisements