w3resource

C Exercises: Calculate the sum of the series [ 1+x+x^2/2!+x^3/3!+....]


23. Sum of Series [ 1+x+x^2/2!+x^3/3!+....].

Write a program in C to display the sum of the series [ 1+x+x^2/2!+x^3/3!+....].

This C program calculates and displays the sum of the series 1+x+x^2/2!+x^3/3!+…. The program prompts the user to input the value of x and the number of terms n. It then computes the sum using a loop, calculating each term by raising x to the appropriate power and dividing by the factorial of the term index. It finally adding it to the cumulative sum. The resulting sum of the series is then printed.

Sample Solution:

C Code:

#include <stdio.h>

// Function to calculate factorial
double factorial(int n) {
    double fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

// Function to compute the sum of the series
double computeSeries(double x, int terms) {
    double sum = 1.0; // First term is always 1
    for (int i = 1; i < terms; i++) {
        sum += (pow(x, i) / factorial(i));
    }
    return sum;
}

int main() {
    double x;
    int n;
    
    // Input from user
    printf("Enter the value of x: ");
    scanf("%lf", &x);
    
    printf("Enter the number of terms: ");
    scanf("%d", &n);
    // Compute and display the sum of the series
    printf("Sum of the series: %.6lf\n", computeSeries(x, n));

    return 0;
}

Output:

Enter the value of x: 2
Enter the number of terms: 5
Sum of the series: 7.000000                                                                                       

For more Practice: Solve these Related Problems:

  • Write a C program to compute the sum of the series x - x³ + x⁵ - … for n terms using an iterative loop.
  • Write a C program to calculate the Taylor series expansion for sin(x) using a loop and display each term.
  • Write a C program to display each term of the alternating series and then compute its total sum.
  • Write a C program to compute the series using recursion for both exponentiation and factorial calculations.

C Programming Code Editor:



Previous: Write a program in C to print the Floyd's Triangle.
Next: Write a program in C to find the sum of the series [ x - x^3 + x^5 + ......].

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.