CPPForSchool.com: Flow of Control Set 3: Assignment 2

2. Write a program to compute sinx for given x. The user should supply x and a positive integer n. We compute the sine of x using the series and the computation should use all terms in the series up through the term involving xn

sin x = x - x3/3! + x5/5! - x7/7! + x9/9! .......


It appears that my math nightmare of the past have come back to haunt me!  All joking aside, it has been over 10 years since I approached any math problems containing sin, cos, tan, etc.  Knowing that I am supposed to use loops for this assignment, I am extremely lost.  Of course, the simple route would be to utilize the math library, but in regards to this exercise it is not an option.  Sadly, even reviewing the sample source code has left me out in the cold.  Nevertheless, I have went ahead and copied the sample source code below.

#include<iostream>
using namespace std;

int main()
{
 int i,j,n,fact,sign=-1;
 float x, p,sum=0;
 cout<<"Enter the value of x : ";
 cin>>x;
 cout<<"Enter the value of n : ";
 cin>>n;

 for(i=1;i<=n;i+=2)
 { 
  p=1;
                fact=1;
  for(j=1;j<=i;j++)
  {
   p=p*x;
   fact=fact*j;
  }
  sign=-1*sign;
  sum+=sign*p/fact;
 }
 cout<<"sin "<<x<<"="<<sum;

 
 return 0;
}

Comments

Popular posts from this blog

CPPForSchool.com: Variable, Operator & Expression Set 1: Assignment 9

CPPForSchool.com: Array - Single Dimension Set 1 Assignment 6

CPPForSchool.com: Variable, Operator & Expression Set 1: Assignment 8