C++ program to get the Sum of series: 1 – x^2/2! + x^4/4! -…. upto nth term


In this tutorial, we will be discussing a program to get the sum of series 1 – x^2/2! + x^4/4! … upto nth term.

For this we will be given with the values of x and n. Our task will be to calculate the sum of the given series upto the given n terms. This can be easily done by computing the factorial and using the standard power function to calculate powers.

Example

#include <math.h>
#include <stdio.h>
//calculating the sum of series
double calc_sum(double x, int n){
   double sum = 1, term = 1, fct, j, y = 2, m;
   int i;
   for (i = 1; i < n; i++) {
      fct = 1;
      for (j = 1; j <= y; j++) {
         fct = fct * j;
      }
      term = term * (-1);
      m = term * pow(x, y) / fct;
      sum = sum + m;
      y += 2;
   }
   return sum;
}
int main(){
   double x = 5;
   int n = 7;
   printf("%.4f", calc_sum(x, n));
   return 0;
}

Output

0.3469

Updated on: 03-Dec-2019

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements