Evaluate F(x) Using Recursion in C – Series Expansion with Factorial

Introduction

In this tutorial, you will learn how to evaluate the function F(x) using recursion in C, where


C Program to Evaluate F(x) Using Recursive Calls

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

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

double power(double x, int n) {
if (n == 0)
return 1;
return x * power(x, n - 1);
}

double evaluateFx(double x, int n) {
if (n == 1)
return x;
return evaluateFx(x, n - 2) + pow(-1, (n - 1) / 2) * power(x, n) / factorial(n);
}

int main() {
double x;
int n;

printf("Enter value of x: ");
scanf("%lf", &x);

printf("Enter the highest odd value of n: ");
scanf("%d", &n);

if (n % 2 == 0) {
printf("Please enter an odd number for n.\n");
return 1;
}

double result = evaluateFx(x, n);
printf("F(x) = %.6lf\n", result);

return 0;
}

Explanation

  • factorial(n): Calculates n! using recursion.
  • power(x, n): Computes xⁿ using recursion.
  • evaluateFx(x, n): Recursively evaluates the alternating series up to term xⁿ/n!.

The series alternates between addition and subtraction based on term index and uses odd values of n only (e.g., 1, 3, 5, …).


Sample Output

Enter value of x: 2  
Enter the highest odd value of n: 7
F(x) = 1.508314

Use Cases

  • Approximating functions like sin(x) or Taylor series expansion.
  • Learning recursion with real-world math-based examples.
  • Helpful in competitive programming and academic exercises.
Previous Article

Exchange Values of Two Variables in C Using Function with Example

Next Article

Factorial Program in C Using Recursion – Simple Code with Explanation

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨