This C program computes the value of sin(x) by summing its Taylor series up to a given accuracy, then compares the result with the built-in sin() library function. It’s a classic exercise in loops, floating-point math, and how a computer approximates trigonometric functions.
The Sine Series
The Taylor series for sine (with x in radians) is:
sin(x) = x - x³/3! + x⁵/5! - x⁷/7! + ...
Each term comes from the previous one by multiplying by -x² / (2n(2n+1)), so there’s no need to compute factorials or powers directly — we just keep adding terms until the sum is accurate enough.
The Program
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
int main(void)
{
int n, deg;
double acc, term, x, sinx, sinval;
printf("Enter the value of x (in degrees) : ");
scanf("%d", °);
printf("Enter the accuracy for the result : ");
scanf("%lf", &acc);
x = deg * (PI / 180.0); /* convert degrees to radians */
sinval = sin(x); /* reference value from the library */
term = x; /* first term of the series */
sinx = term;
n = 1;
do {
term = -term * x * x / (2.0 * n * (2.0 * n + 1.0));
sinx += term;
n++;
} while (fabs(sinval - sinx) >= acc);
printf("Sum of the sine series = %lf\n", sinx);
printf("Using library function sin(%d) = %lf\n", deg, sinval);
return 0;
}
How the Program Works
- The angle is read in degrees and converted to radians, because C’s
sin()works in radians. termstarts atx(the first series term). Each pass multiplies it by-x² / (2n(2n+1))to get the next term and adds it tosinx.- The loop stops once the running sum is within
accof the library’ssin(x), giving you control over the accuracy. - We use
doubleand a full-precision π constant for accuracy, improving on the old3.142value.
Compiling (link the math library)
On Linux and macOS, link the math library with -lm:
gcc sinx.c -o sinx -lm
Sample Output
Enter the value of x (in degrees) : 30 Enter the accuracy for the result : 0.00001 Sum of the sine series = 0.500000 Using library function sin(30) = 0.500000
For a clear explanation of C’s numeric types and the math library, The C Programming Language by Kernighan and Ritchie is the classic reference — find it on Amazon.
This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.
Related C Programs
Try it in one of the best online C compilers, or build a local setup with our complete C development environment guide.