I've just started learning c++ this week from the book, c++ from the beginning by jan skansholm, im working througth the exercises and have become stuck on this one:

sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ..................

write a program to calculat sin(x), dont include terms in the sum less than 10^-5.

like I said im new to all of this so don't know where the problem(s) is.
the first program i tried was using a for loop:

#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;

int main()

{
    const double epsilon = 1.0e-5;
    
    double next_term, sum, x;
    int fac, k, sign=1;
    
    cout << "enter value for x: ";
    cin >> x;
    
    next_term = x;
    sum = x;
    fac = 1;
    
    
    for (k=3; fabs(next_term)>=epsilon; k+=2)
    {
        
        for (int c=1; c<=k; c++)
                 fac*=c;
           
    next_term = pow(x,k)/fac;
    
    
    sum = sum+(next_term*sign);
    
    sign = sign*-1;
    
    }
    
    
    
    cout << "sign(x) is:  "  << sum <<endl;
    
    
    
    system("pause");
    return 0;
    
}

i run the program and get nothing after i type in x.

then i tried a while loop:-

#include <iostream>
#include <stdlib.h>
using namespace std;
#include <math.h>

int main()

{
    
    double fac, k, next_term, x, sum=0;
    int sign=1;
    
    cout<<"enter x:    ";
    cin >>x;
    
    fac=1;
    k=1;
    
    
    while(fabs(next_term)>0.0001)
    {
         for (int c=1; c<=k; c++)
             fac*=c;
             
            
    next_term = ((pow(x,k))/fac)*sign;
    sum = sum + next_term; 
    
    sign = sign*-1;
    k=k+2;
    }
    
    cout << "\n\n\nresult is:  " << sum;
    
system ("pause");
return 0;

}

fac=factorial, like 3! = 6

I'm obviously missing something or missing several things, any help would be great, thanks in advanced.

Brilliant thanks alot, I've seem to have it working;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.