Problem 45

author
By Supreme2023-03-15
Problem Statement :
Write a C program to use recursive calls to evaluate F(x) = x – x^ 3 / 3! + x^5 / 5 ! – x^ 7 / 7! + … x^n / n!.
Code:

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

double factorial(int n);
double evaluateF(double x, int n);

int main() {

//evaluate the function F(x) = x - x^3/3! + x^5/5! - x^7/7! + ... x^n/n!

printf("\tEvaluate Series");
printf("\n====================================\n\n");

double x;
int n;

printf("Enter The Value Of X : ");
scanf("%lf",&x);

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

double result = evaluateF(x, n);

printf("\n------------------------------------\n\n");
printf("F(%.2lf) = %.2lf\n", x, result);
printf("\n------------------------------------\n");

return 0;
}

double factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

double evaluateF(double x, int n) {
if (n == 0) {
return x;
} else {
return pow(x, n) / factorial(n) - evaluateF(x, n - 2);
}
}

Description :
  • This program defines two functions, factorial and evaluateF, and a main function that evaluates the value of a function F(x) for a given value of x and number of terms n. The program includes the header files stdio.h and math.h.
  • The program includes the header files stdio.h and math.h, which provide input/output and mathematical functions, respectively.
  • The function factorial is defined, which calculates the factorial of an integer n using recursion.
  • The function evaluateF is defined, which calculates the value of the function F(x) using recursion and the factorial function. The function takes in two parameters, x and n.
  • The main function is defined, which does the following: a. Prints a header message. b. Prompts the user to input the value of x. c. Prompts the user to input the number of terms n. d. Calls the evaluateF function, passing in x and n. e. Prints the result of F(x) to the console.
  • The factorial function calculates the factorial of n using recursion.
  • The evaluateF function calculates the value of the function F(x) using recursion: a. If n is 0, then the function returns x. b. Otherwise, the function calculates the next term of the series using pow(x, n) and factorial(n) and subtracts the result of evaluateF(x, n-2) from it. This recursive call calculates the next term in the series.
  • The main function calculates the value of F(x) and prints it to the console.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.