On 11/27/05, Beav Petrie <[EMAIL PROTECTED]> wrote:
Sluggers,
I run these codes I copied from a tutorial book.
The print out is 24, correct factorial of 4 (4*3*2*1).
But y is 0 (y < 1) finally and return value of 1 so how is it
24 instead of 1 is printed ?
Please help me understand. Many thanks.
Do not flame me, please. I am a newbie.
Beav
Hi Beav,
Factorial is a recursive function.
So, what happens when you say
factorial(4) (in main) ?
Your factorial function returns y*factorial(y-1), so you get:
factorial(4) = 4 * factorial(3).
Now you have to solve factorial(3), which also uses y*factorial(y-1), so:
factorial(3) = 3 * factorial(2)
So substitute this back into the previous _expression_:
factorial(4) = 4 * ( 3 * factorial(2) )
Keep solving factorail for y = 2,1...
Eventually you get
factorial(4) = 4 * ( 3 * ( 2 * 1 * factorial(0) ) )
and as you said,
factorial(0) returns 1 (as it should mathematically ie 0! )
Hope that helps.
Daniel
-- SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/ Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html