w3resource

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

C For Loop: Exercise-23 with Solution

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> // Include the standard input/output header file.

void main()
{
    float x, sum, no_row; // Declare variables to store input and intermediate results.

    int i, n; // Declare loop control variables.

    printf("Input the value of x :"); // Prompt the user for input.
    scanf("%f", &x); // Read the value of 'x' from the user.

    printf("Input number of terms : "); // Prompt the user for input.
    scanf("%d", &n); // Read the value of 'n' from the user.

    sum = 1; // Initialize 'sum' to 1 as the first term in the series.

    no_row = 1; // Initialize 'no_row' to 1 for the first term calculation.

    for (i = 1; i < n; i++) // Loop to calculate subsequent terms in the series.
    {
        no_row = no_row * x / (float)i; // Calculate the next term using the given formula.
        sum = sum + no_row; // Add the term to the running sum.
    }

    printf("\nThe sum is : %f\n", sum); // Print the final sum.
}

Output:

Input the value of x :3                                                                                       
Input number of terms : 5                                                                                     
                                                                                                              
The sum  is : 16.375000                                                                                       

Flowchart:

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

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.