This C program computes the value of cos(x) by summing its Taylor series up to a given accuracy, then checks the result against the built-in cos() library function. It’s a great exercise in loops, floating-point arithmetic, and how mathematical functions are actually approximated inside a computer.
The Cosine Series
The Taylor series for cosine (with x in radians) is:
cos(x) = 1 - x²/2! + x⁴/4! - x⁶/6! + ...
Each term is built from the previous one by multiplying by -x² / (2n(2n-1)), so we never have to compute factorials or powers directly — we just keep refining the sum until it is close enough to the library value.
The Program
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
int main(void)
{
int n, deg;
double acc, term, x, cosx, cosval;
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 */
cosval = cos(x); /* reference value from the library */
term = 1.0; /* first term of the series */
cosx = term;
n = 1;
do {
term = -term * x * x / (2.0 * n * (2.0 * n - 1.0));
cosx += term;
n++;
} while (fabs(cosval - cosx) >= acc);
printf("Sum of the cosine series = %lf\n", cosx);
printf("Using library function cos(%d) = %lf\n", deg, cosval);
return 0;
}
How the Program Works
- The angle is entered in degrees and converted to radians (
x = deg * PI / 180), because C’scos()expects radians. termstarts at 1 (the first series term). Each iteration multiplies it by-x² / (2n(2n-1))to get the next term and adds it tocosx.- The loop keeps adding terms until the running sum is within
accof the library’scos(x)— that is how we control accuracy. - We use
double(notfloat) and a full-precision value of π for an accurate result, improving on the old3.142constant.
Compiling (link the math library)
On Linux and macOS you must link the math library with -lm:
gcc cosx.c -o cosx -lm
Sample Output
Enter the value of x (in degrees) : 60 Enter the accuracy for the result : 0.00001 Sum of the cosine series = 0.500000 Using library function cos(60) = 0.500000
For a solid grounding in C’s numeric types and the math library, The C Programming Language by Kernighan and Ritchie remains 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.