C program for Cosine Series
Before going to the program for Cosine Series first let us understand what is a Cosine Series?
Cosine Series:
Cosine Series is a series which is used to find the value of Cos(x).
where, x is the angle in degree which is converted to Radian.
The formula used to express the Cos(x) as Cosine Series is
Expanding the above notation, the formula of Cosine Series is
For example,
Let the value of x be 30.
So, Radian value for 30 degree is 0.52359.
So, the value of Cos(30) is 0.8660.
Program code for Cosine Series in C:
#include<stdio.h> #include<conio.h> void main() { int i, n; float x, sum=1, t=1; clrscr(); printf(" Enter the value for x : "); scanf("%f",&x); printf(" Enter the value for n : "); scanf("%d",&n); x=x*3.14159/180; /* Loop to calculate the value of Cosine */ for(i=1;i<=n;i++) { t=t*(-1)*x*x/(2*i*(2*i-1)); sum=sum+t; } printf(" The value of Cos(%f) is : %.4f", x, sum); getch(); }
Related: C program for Sine Series
Working:
- First the computer reads the value of ‘x’ and ‘n’ from the user.
- Then ‘x’ is converted to radian value.
- Then using for loop the value of Cos(x) is calculate.
- Finally the value of Cos(x) is printed.
Related: C program for Exponential Series
Step by Step working of the above Program Code:
Let us assume that the user enters the value of ‘x’ as 30 and ‘n’ as 4.
- Converting ‘x’ to radian value
x = x * 3.14159 / 180 (x = 30 * 3.14159 / 180) So, x=0.52359
- It assigns t=1 and sum=1
- It assigns the value of i=1 and the loop continues till the condition of the for loop is true.
3.1. i<=n (1<=4) for loop condition is true
t = (1 * (-1) * 0.52359 * 0.52359)/(2 * 1 * (2 * 1 – 1))
So, t = – 0.13707
sum = 1 + (- 0.1370)
So, sum=0.86293
i++
So, i=2
3.2. i<=n (2<=4) for loop condition is true
t = (- 0.13707 * (-1) * 0.52359 * 0.52359)/(2 * 2 * (2 * 2 – 1))
So, t = 0.00313
sum = 0.86293 + 0.00313
So, sum=0.86606
i++
So, i=3
3.3. i<=n (3<=4) for loop condition is true
t = (0.00313 * (-1) * 0.52359 * 0.52359)/(2 * 3 * (2 * 3 – 1))
So, t = – 0.000028
sum = 0.86606 + (- 0.000028)
So, sum=0.86603
i++
So, i=4
3.4. i<=n (4<=4) for loop condition is true
t = (-0.000028 * (-1) * 0.52359 * 0.52359)/(2 * 4 * (2 * 4 – 1))
So, t = 0.000000137
sum = 0.86603 + 0.000000137
So, sum=0.866030137
i++
So, i=5
3.5. i<=n (5<=4) for loop condition is false
It comes out of the for loop.
- Finally it prints The value of Cos(0.52359) is : 0.8660
- Thus program execution is completed.
Output:
TO DOWNLOAD THE PROGRAM CODE : CLICK HERE
Useful