﻿ C : Compute the sum of the series [ 1-X^2/2!+X^4/4!- ...]

# C Exercises: Calculate the sum of the series [ 1-X^2/2!+X^4/4!- .........]

## C For Loop: Exercise-18 with Solution

Write a program in C to find the sum of the series [ 1-X^2/2!+X^4/4!- .........].

Sample Solution:

C Code:

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

int main() {
float x, sum, t, d;  // Declare variables to store input and intermediate values.
int i, n;  // Declare variables for loop control and input.

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

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

sum = 1;  // Initialize 'sum' to 1, as the first term is always 1.
t = 1;    // Initialize 't' to 1 for the first term.

// Loop to calculate the sum of the series.
for (i = 1; i < n; i++) {
d = (2 * i) * (2 * i - 1);  // Calculate the denominator for the term.
t = -t * x * x / d;        // Calculate the term value.
sum = sum + t;             // Add the term to the sum.
}

// Print the final result along with the input values.
printf("\nThe sum = %f\nNumber of terms = %d\nValue of x = %f\n", sum, n, x);

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

```
```

Flowchart: or

``````#include <stdio.h>
int main()
{
// Variable declaration
float x, s, t, num = 1.00, fac = 1.00;
int i, n, pr, y = 2, m = 1;

// User input for x and the number of terms
printf("Input the Value of x: ");
scanf("%f", &x);
printf("Input the number of terms: ");
scanf("%d", &n);

// Initializing variables for summation
s = 1.00;
t = 1.00;

// Loop to calculate the sum based on the number of terms
for (i = 1; i < n; i++)
{
// Loop to calculate factorial and power of x
for (pr = 1; pr <= y; pr++)
{
fac = fac * pr; // Calculate factorial
num = num * x;  // Calculate power of x
}

m = m * (-1);    // Alternate the sign for the power of x
num = num * m;   // Applying the alternating sign
t = num / fac;   // Calculate the term value for this iteration
s = s + t;       // Add the term value to the sum
y = y + 2;       // Increment for the next odd number (power of x)
num = 1.00;      // Resetting num for the next iteration
fac = 1.00;      // Resetting fac for the next iteration
}

// Output the result
printf("\nThe sum = %f\nNumber of terms = %d\nValue of x = %f\n", s, n, x);

return 0;
}
```
```

Sample Output:

```Input the Value of x :2
Input the number of terms : 5

the sum = -0.415873
Number of terms = 5
value of x = 2.000000
```

Flowchart: C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿