Skip to main content

Cosine series up to n terms

Short answer

Compute cos(x) using series: start term=1, sum=1. Each new term = previous * (-x^2)/((2i-1)(2i)). For x=1.0 rad and 8 terms, the sum equals 0.540302.

Write a program in C-programming language to compute the cosine series. (hints: cos(x) = 1-x²/2!+x⁴/4!-x⁶/6!+…………up to n terms)

cos(x) = 1 - x²/2! + x⁴/4! - x⁶/6! + ... (x in radians). Instead of calculating factorials and powers separately, each term is obtained from the previous one:

term(i) = term(i-1) × (-x²) / ((2i-1)(2i)), with term(0) = 1

so the program needs only one loop.

#include <stdio.h>
#include <math.h>
int main(void)
{
    int n, i;
    double x, term = 1.0, sum = 1.0;
    printf("Enter x (in radians) and number of terms: ");
    scanf("%lf %d", &x, &n);
    for (i = 1; i < n; i++)
    {
        /* next term = previous term * (-x*x) / ((2i-1)(2i)) */
        term = term * (-x * x) / ((2 * i - 1) * (2 * i));
        sum += term;
    }
    printf("cos(%.2f) by series = %.6f\n", x, sum);
    printf("cos(%.2f) by library = %.6f\n", x, cos(x));
    return 0;
}

Output for x = 1.0 and 8 terms:

Enter x (in radians) and number of terms: cos(1.00) by series = 0.540302
cos(1.00) by library = 0.540302

The series value matches the library cos() value.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →