Header Ads

Print the sum of series using C programming

 1! - x^2/2! + x^4/4! - x^6/6! ...... 

To solve the above series using C programming first we have to identify the patterns and general terms in the series. Three things are to be kept in mind while writing the code for the above problem.
  1. The power of x in each term is increased by 2.
  2. In the denominator, there is a factorial of the same number, the power of the x.
  3. The odd term has a positive sign while the even period has a negative Sign.


Code :

// Print the sum of series
// 1/1! - x^2/2! + x^4/4! - x^6/6! ......

#include<stdio.h>
#include<math.h>

// function to calculate factorial
int fact(int f);

int main(){
int i,n,x,p = 0, v = 0;
float sum = 0.0;
printf("Enter number of terms : ");
scanf("%d",&n);
printf("Enter the value of x : ");
scanf("%d",&x);
for(i=0;i<n;i++){
float po = (float)(pow(x,v));
float fac = fact(v);
if(i%2==0){
sum = sum + po/fac;
} else{
sum = sum - po/fac;
}
v+=2;
}
printf("Sum of the series = %f",sum);
return 0;
}

int fact(int f){
int i, fac = 1;
for(i=1;i<=f;i++)
fac=fac*i;
return fac;
}


Output :

Enter number of terms : 4
Enter the value of x : 3
Sum of the series = -1.137500

Explanation :

This code calculates the sum of a mathematical series. The series is defined as follows:

1/1! - x^2/2! + x^4/4! - x^6/6! ......

The series continues until the number of terms is specified by the user. The value of x is also provided by the user.

The main() function prompts the user for the number of terms and the value of x, then uses a for loop to iterate over the terms of the series. For each term, it calculates the power of x and the factorial that appears in the term, then adds or subtracts the term from the sum depending on whether the term index is even or odd. Finally, it prints the sum to the screen.

The fact() function is a helper function that calculates the factorial of a number. It takes an integer as input and returns the factorial of that number as output.




Related Links :

Define a class to declare a character array of size ten, accept the character into the array and perform the following: • Count the number of uppercase letters in the array and print. • Count the number of vowels in the array and print.





Post a Comment

0 Comments