C Program to Compute Cosine Series

The program to compute cosine series is based on mathematical concept of sequences and series – particularly power series.

This program is written using Dev-C++ compiler, but you can use any standard C compiler to compile and run the program. This program is intended for beginners as well as intermediate learners of C programming.

To help you learn, we have following sections – problem definition, flowchart, program source code and verified output of the program.

Problem Definition

Cosine series is a power series known as the Maclaurin expansion of Cos(x) where x is a real number value. Given the value of x, the series will converge and give a finite value ( radius of convergence) for the series.

cos(x) = k=0= (-1)kx2k/(2k)! = 1 – x2/2! +  x4/4! – x6/6! … 

We won’t be discussing, how terms of the series are generated because that would be topic for another post. The Maclaurin expansion for cos(x) is for x =0, however, it is true for all real values of x.

In other words, it is same as finding the value of trigonometric ratio of cos θ, the cosine series will give you a better approximate value of cos θ.



Flowchart - C Program for Cosine Series
Flowchart – C Program for Cosine Series

Program Code

/* Program to compute cosine series */  /* cos(x) = 1-x^2/2!+x^4/4!+x^6/6!+...+x^n/n! */  #include <stdio.h>  #include <stdlib.h>  #include <math.h>    main()  {      float x, t, sum;      int d;      int i, n=20;        /* Read the Input x value in degrees */        printf ("Input X Value (in degrees) :");      scanf ("%f", &x);      d= x;        /*converting x to radians */        x=x*3.1412/180;      t=1;      sum=1;        for (i=1; i<n+1; i++)      {          t=t*pow ((double) (-1), (double) (2*i-1))*x*x/ (2*i*(2*i-1));            sum=sum+t;      }        /* Print the Results */        for (i =0; i<35; i++)      printf ("_"); printf ("\n\n");        printf ("COS (%d) =%7.3f\n\n", (int) d, sum);        for (i =0; i<35; i++)      printf ("_"); printf ("\n\n");        system ("PAUSE");      return 0;  }


The output of the program is given below.

Output - C Program for Cosine Series
Output – C Program for Cosine Series