Wednesday 18 June 2014

C++ program to evaluate sine series

Here are C++ program to calculate sine of the angle. First program calculate sine of the angle using sine() function, second program evaluate sine series(you can enter the accuracy for the result) and third program uses recursion to evaluate sine series.


C++ program calculate sine of the angle using sine() function

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    double y,temp,x;
    cout<<"Enter the value of x ";
    cin>>x;
    y=x;
    x=x*3.142/180;
    temp=sin(x);
    cout<<"sine("<<y<<") = "<<temp;
    return 0;
}



C++ program evaluate sine series

#include<iostream>
#include<math.h>
using namespace std;
long double factorial(int n)
{
    long double fact=1;
    while(n>0)
    {
        fact*=n;
        n--;
    }
    return fact;
}
int main()
{
    float temp=0,x,n,y=1,z;
    cout<<"Enter the value of x ";
    cin>>x;
    cout<<"Enter the value of n ";
    cin>>n;
    z=x;
    x=x*22/(180*7);
    for(int i=1;i<=n;i+=2)
    {
         temp+=y*pow(x,i)/(1.0*factorial(i));
         y=-y;
    }
    cout<<"sine("<<z<<") = "<<temp;
    return 0;
}



C++ program evaluate sine series using recursion

#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
long double factorial(int n)
{
    long double fact=1;
    while(n>0)
    {
        fact*=n;
        n--;
    }
    return fact;
}
void sins(float &temp,int y,float x,int i,int n)
{
    if(i>n)
        return;
    temp+=y*pow(x,i)/(1.0*factorial(i));
    sins(temp,-y,x,i+2,n);
}
int main()
{
    float temp=0,x;
    int n;
    cout<<"Enter the value of x ";
    cin>>x;
    cout<<"Enter the accuracy for the result ";
    cin>>n;
    sins(temp,1,x*22/(180*7),1,n);
    cout<<setprecision(3)<<"sine("<<x<<") = "<<temp;
    return 0;
}


1 comment: