Here's a C program to calculate the cosine series with output. This program makes use of C concepts like For loop. The program also uses C's math.h header file and power function

**pow(i, j).**

**Formula of Cosine Series:**The formula for cosine series is -

Cosine Series |

# include <stdio.h> # include <conio.h> # include <math.h> void main() { int i, n ; float x, val, sum = 1, t = 1 ; clrscr() ; printf("Enter the value for x : ") ; scanf("%f", &x) ; printf("\nEnter the value for n : ") ; scanf("%d", &n) ; val = x ; x = x * 3.14159 / 180 ; 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 ; } printf("\nCosine value of %f is : %8.4f", val, sum) ; getch() ; }

**Output of above program is**

Enter the value for x : 60

Enter the value for n : 20

Cosine value of 60.000000 is : 0.5000

**Explanation of above program**

Let

*n*= 3, then the sine series generated by above program is as follows:
Initially,

*x*is converted to radian by multiplying it by 3.14159/180 and*t*and*sum*are also assigned the value of*1*. So, after line no 16 of the program, we have:*t =*1 and

*sum =*1

Now lets take a look at the working of for loop with

*n*= 3:
Exp 1: t = t * pow((double) (-1), (double) (2 * i - 1)) * x * x / (2 * i * (2 * i - 1))

Exp 2: sum = sum + t

**Iteration 1: i = 1, t = 1, sum =1**

Putting these values in Exp 1 we get,

t = 1 * pow((double) (-1), (double) (2 * 1 - 1)) * x * x / (2 * 1 * (2 * 1 - 1))

t = 1*(-1)*x*x/2 = -x

^{2}/2!
Putting value of t in Exp 2 we get,

sum = 1 + (-x

^{2}/2! ) = 1 - x^{2}/2!**Iteration 2: i = 2, t =**

**-x**

^{2}/2!, sum = 1 - x^{2}/2!
Putting these values in Exp 1 we get,

t = (-x

^{2}/2!) * pow((double) (-1), (double) (2 * 2 - 1)) * x * x / (2 * 2 * (2 * 2 - 1))
t = -x

^{2}/2!*(-1)*x*x/12 = x^{4}/4!
Putting value of t in Exp 2 we get,

sum = 1 - x

^{2}/2! + x^{4}/4!**Iteration 3: i = 3, t =**

**x**

^{4}/4!, sum = 1 - x^{2}/2! +

**x**^{4}/4!
Putting these values in Exp 1 we get,

t = x

^{4}/4! * pow((double) (-1), (double) (2 * 3 - 1)) * x * x / (2 * 3 * (2 * 3 - 1))
t = x

^{4}/4!*(-1)*x*x/30 = x^{6}/6!
Putting value of t in Exp 2 we get,

sum = 1 - x

^{2}/2! + x^{4}/4! - x^{6}/6!
After iteration 3, i = 4 so the for loop terminates and output is printed.

y double is used there?

To avoid precision/accuracy loss to some extent and also unexpected behavior caused while storing floating point values in memory.

how to do the same cosx nd sinx series using do-while loop??

Just initialize i with 1 outside the loop and replace the for loop as follows:

i = 1;

do{

t = t * pow((double) (-1), (double) (2 * i - 1)) *

x * x / (2 * i * (2 * i - 1)) ;

sum = sum + t ;

i++;

}while( i < n + 1);

Hope it works.