WAP to compute the cosine series using function.
=1-x2/2!+x4/4!-x6/6!----
Objective
Write a C++ program to compute the Cosine Series.
Algorithm / Approach
- Include
<math.h>. - Define a factorial function.
- Define a
cal_cos(x, n)function. - Use a loop to calculate terms. If the iteration is even, add the term. If odd, subtract the term to create the alternating +/- pattern.
- Return the sum.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
float cal_cos(int, int);
int fact(int);
int main( )
{
int x, n;
cout<<"Enter the value of x : ";
cin>>x;
cout<<"Enter the value of n : ";
cin>>n;
float r = cal_cos(x, n);
cout<<"Result = "<< r;
return 0;
}
float cal_cos(int a, int n) {
int i,j =2 ;
float sum = 1;
for(i=1; i<=n; i++)
{
if(i%2 ==0)
{
sum = sum+pow(a,j)/(float)fact(j);
}
else
{
sum = sum-pow(a,j)/fact(j);
}
}
return sum;
}
int fact(int x){
int i, f=1;
for(i=1; i<=x; i++){
f = f*i;
}
return f;
}
Expected Output
Enter the Value of x : 3 Enter the Value of n : 3 Result = -1.250000
Explanation of the Program
- The Cosine series (from Taylor Series expansion) relies on alternating addition and subtraction of terms.
- By using the modulo operator (
i % 2 == 0) inside the loop, the program can automatically switch between adding the next term and subtracting the next term.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)