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!+....].

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

int 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.

    return 0; // Return 0 to indicate successful execution.
}


Sample 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.