I am learning recursion, and at
cprogramming.com tut 16 the end of the lesson they give you a problem to solve.
Here is a copy so you dont need to click:
Quote:
This is just the beginning of the usefulness of recursion. Heres a little challenge, use recursion to write a program that returns the factorial of any number greater than 0. (Factorial is number*number-1*number-2...*1).
So I wanted to know if the code I wrote will work, I'm at work right now so I dont get to run it throught the compiler, but I think I have that part right anyway :).
The first one should be stright-to-the-point, the second one was for fun, I wanted to write the function w/o having to use a constant (ie, > 1, == 0, return 1). So the second was *should* do the same, I just wanted a little bit of a challenge. :)
Please let me know what you think.
// calculates facoral
// my first recursave function.
int func_fact (int tfact)
{
if(tfact > 1)
return tfact * func_fact(tfact-1);
else
return 1;
}
int func_factx (int tfact)
{
int afact = tfact;
afact--; // make afact one less than tfact
if((afact + afact)) // if afact is not 0, keep solving
return tfact * func_fact(afact);
else // if afact is zero, then tfact is 1
return tfact;
}
Thank you!
EDIT:
the func_factx does not check for tfact == 0 before afact--.
in the case of func_factx(0) called, then afact= tfact (=0), so when afact--; (= -1), then the (afact + afact) will = -2, will this cause the if statement to take a -2 as FALSE?