You already know you have to do a loop from 1 to some maximum n.
Look closely at how the numbers change each time :
Code:
1(x^0)/0!
2(x^2)/1!
3(x^4)/2!
4(x^6)/3!
5(x^8)/4!
and so on. There's a pattern there you should use.
You've got 3 terms that are changing. The first one goes from 1 to 2 to 3 to 4. Call this term_a, each time through the loop you use this to calculate the current term, then add 1 to it for next time through.
term_b goes from 1 to x^2 to x^4 to x^6 up to x^2n. In other words, each time through the loop you multiply it by x^2.
Third term is a little strange, it goes from 1 to 1 to 2 to 6 to 24 .... If you number the loops starting at 1, each time after you use it you multiply it by the loop number to get the value to use next time through the loop.
The add/subtract alternating stuff can be handled by a 4th term. Set this to 1 initially and multiply it by -1 each time through the loop so that you alternate between adding and subtracting.
In pseudo-code :
Code:
double function(double x, int n)
{
All of the individual bits of the equation start at 1 but
change at different rates
int sign = 1;
double term_a = 1.0;
double term_b = 1.0;
double term_c = 1.0;
double result = 0.0; <- this is the running total
double this_term; <- this is the current term you're calculating.
for each foo from 0 to n do <- foo is just a loop counter here, goes from 0 to 1 to 2 up to N
{
calculate this_term = sign x term_a x term_b / term_c
add this_term to result
multiply sign by -1
add 1 to term_a
multiply term_b by x^2
multiply term_c by foo + 1 <- this is because C loops start
counting at 0, but you really want to
count loops starting at 1 for this 1 term.
}
return result;
}
You could also go through the hassle of re-calculating each term each time through the loop doing something like this, but I'm sure this isn't what your teacher wants. At the same time it would be a useful exercise to try and see if you can make both methods match. An even better exercise - write a main() program which calls both versions and compares the answer to verify that both functions work the same way.
Code:
for each foo from 0 through N
{
sign = 1;
for each i from 0 through foo
sign = -sign;
coefficient = foo
x_to_n = 1;
for each i from 0 through 2 * foo
x_to_n = x_to_n * x
n_factorial = 1
for each i from 1 through foo
n_factorial = n_factorial * i
result = result + sign * coefficient *x_to_n / n_factorial
}