C Program to Evaluate the Series 1 – x + x²/2! – x³/3! + … – x⁹/9!

Introduction

In this blog, you will learn how to write a C program to evaluate the series:
sum = 1 – x + x²/2! – x³/3! + x⁴/4! – x⁵/5! + … – x⁹/9!

This series features alternating signs, increasing powers of x, and factorials in the denominators. Such series are common in scientific computing and Taylor series expansions.


Problem Statement

Create a C program to evaluate the following mathematical expression:
sum = 1 – x + x²/2! – x³/3! + x⁴/4! – x⁵/5! + … – x⁹/9!

The input is a number x provided by the user.


C Program to Evaluate the Series

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

int main() {
int i, sign = -1;
float x, sum = 1.0, term;
long factorial;

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

for (i = 1; i <= 9; i++) {
factorial = 1;

for (int j = 1; j <= i; j++) {
factorial *= j;
}

term = pow(x, i) / factorial;

if (i % 2 == 0)
sum += term;
else
sum -= term;
}

printf("The value of the series is: %.4f\n", sum);

return 0;
}

Code Explanation

  • User Input: Accepts the value of x
  • Loop: Runs from 1 to 9
  • Factorial: Calculated using an inner loop
  • Term Calculation: Uses pow(x, i) and factorial
  • Sign Handling: Alternates signs using if (i % 2 == 0)
  • Sum: Adds or subtracts the current term from the total

Output Example

Enter the value of x: 2  
The value of the series is: 0.2333

Why This Program Is Useful

  • Helps understand nested loops and mathematical functions
  • Demonstrates series expansion and alternating signs
  • Reinforces concepts of factorials and exponents in programming
  • A great exercise for mathematics and C language learners


Conclusion

This C program to evaluate series using alternating signs, powers, and factorials is a classic example of applying mathematical logic with loops. It is ideal for those learning C and aiming to understand more complex math-based programming problems.

Previous Article

C Program to Find the Sum of Series 1 + 1/2! + 1/3! + … + 1/n!

Next Article

C Program to Print Star Patterns Using Nested Loops

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 ✨