PPS Lab · Experiment 15
Sum of the series 1 - x/2 + x²/4 - x³/6
CExpression evaluationJNTUH R22 · CS108ES
Aim
To write a C program that reads a fractional value x and calculates the sum of the series 1 − x/2 + x²/4 − x³/6.
Algorithm
- Read x.
- Find each term: term1 = 1, term2 = −x/2, term3 = x²/4, term4 = −x³/6.
- Add the four terms to get the sum.
- Print each term and the sum.
Program
#include <stdio.h>
#include <math.h>
int main(void) {
double x;
printf("Enter the value of x: ");
if (scanf("%lf", &x) != 1) {
printf("Invalid input\n");
return 1;
}
double term1 = 1;
double term2 = -x / 2;
double term3 = pow(x, 2) / 4;
double term4 = -pow(x, 3) / 6;
double sum = term1 + term2 + term3 + term4;
printf("Terms: %.4f, %.4f, %.4f, %.4f\n", term1, term2, term3, term4);
printf("Sum of 1 - x/2 + x^2/4 - x^3/6 = %.4f\n", sum);
return 0;
}Output
x = 0.5
Enter the value of x: 0.5
Terms: 1.0000, -0.2500, 0.0625, -0.0208
Sum of 1 - x/2 + x^2/4 - x^3/6 = 0.7917x = 2
Enter the value of x: 2
Terms: 1.0000, -1.0000, 1.0000, -1.3333
Sum of 1 - x/2 + x^2/4 - x^3/6 = -0.3333Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
The program computes exactly the four terms given in the syllabus. Check of the first run by hand: 1 − 0.25 + 0.0625 − 0.0208 = 0.7917.
After the first term the series follows a pattern: the k-th extra term is x^k / (2k), with the sign changing each time (minus, plus, minus, ...). To add more terms, use a loop for k = 1, 2, 3, ..., keep sign as −1 or +1 and flip it each time, and add sign * pow(x, k) / (2 * k).
Common mistakes
Writing
x^2for x squared. In C^is bitwise XOR and does not even work on adouble. Usepow(x, 2)orx * x.Declaring x as
int. The question says x is fractional, and anintwould also makex / 2an integer division.Writing
pow(x, k) / 2 * kin a loop version. Division and multiplication go from left to right, so this is (x^k / 2) × k. Put the denominator in brackets:pow(x, k) / (2 * k).Forgetting
-lmon Linux when usingpow, which gives the linker errorundefined reference to pow.
Viva questions
Try to answer each one aloud before you open it.
How do you find the power of a number in C?
With
pow(base, exponent)frommath.h, which returns adouble. For small whole powers, repeated multiplication such asx * x * xalso works.What is the value of the series when x = 0?
Every term except the first becomes 0, so the sum is 1.
What is the pattern in this series?
After the 1, the k-th term is x^k divided by 2k, and the signs alternate starting with minus: −x/2, +x²/4, −x³/6, and so on.
Why is the data type double used for x?
x is a fractional value, and the terms involve division, so the results have fractional parts.
doublestores these with good precision.