Problem 28

author
By Supreme2023-03-15
Problem Statement :
Write a program to evaluate the series sum=1-x+x^2/2!-x^3/3!+x^4/4!......-x^9/9!
Code:

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

float series (float x, int n);

int main(){
printf("\t\tEvaluation Of Given Series");
printf("\n\t1 - x + x^2/2! - x^3/3! + x^4/4!......- x^9/9!");
printf("\n============================================================\n");
float x;
int n=9;

printf("\nEnter The Value Of X : ");
scanf("%f",&x);

float answer = series (x,n);

printf("\nAnswer = %.4f ",answer);
return 0;
}

float series(float x,int n){
float sum=1,sign=1,fact,j,y=1,term;
int i;

for(i=1;i<=n;i++){
fact=1;
for(j=1;j<=y;j++){
fact *= j;
}

sign = pow((-1),i);
term = sign*pow(x,y)/fact;
sum += term;
y++;
}
return sum;
}

Description :
  • This program evaluates the given series: 1 - x + x^2/2! - x^3/3! + x^4/4! - x^5/5! + x^6/6! - x^7/7! + x^8/8! - x^9/9!
  • The program includes two libraries: stdio.h and math.h.
  • The main function starts by printing the series to be evaluated.
  • It prompts the user to input the value of x.
  • It initializes the number of terms in the series (n) to 9.
  • It calls the series function and passes the values of x and n to it.
  • The series function takes two arguments: x and n, and returns the sum of the series.
  • Inside the series function, it initializes the first term of the series to 1.
  • It declares some variables including sign, fact, j, y, and term.
  • It starts a loop from i=1 to n.
  • It initializes the factorial (fact) to 1.
  • It calculates the factorial of y by starting another loop from j=1 to y.
  • It multiplies the factorial by j for each iteration.
  • It calculates the sign of the term based on the current iteration of i.
  • It calculates the term by raising x to the power of y, multiplying by the sign, and dividing by the factorial.
  • It adds the term to the sum.
  • It increments y by 1 for the next iteration.
  • After the loop is completed, the function returns the sum of the series.
  • Finally, the main function prints the result returned by the series function.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.