Beav Petrie was once rumoured to have said:
> 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.
This is a case of recursion.
Lets just focus on int factorial(int y) --
(cleaned up from prior post)
---CODE---
int
factorial(int y)
{
if (y < 1) {
return 1;
} else {
return (y * factorial(y - 1));
}
}
---END CODE---
First, lets look at the declaration:
int factorial(int y)
This is defining a function that takes a single integer, and returns
an integer.
There are no local variables fined.
next, we have an if statement:
if (y < 1) {
...
This is defining a boundary case: if y is less than 1, then the result is 1.
now, lets look at the else:
return (y * factorial(y - 1));
So, if y >= 1, the result is y * factorial(y-1).
note the recurisve call to factorial() with a value one less than y?
This with the previous if(...) statement forms the basis for the
recursive funciton.
So,lets look at x=1:
factorial(1) ->
1
1! is 1, so this is fine.
lets expand this for x = 2 and x = 3...
factorial 2 ->
2 * factorial(1)
2 * (1 * factorial(0))
2 * (1 * 1)
2 * 1
2
factorial 3 ->
3 * factorial(2)
3 * (2 * factorial(1))
3 * (2 * (1 * factorial(0)))
3 * (2 * (1 * 1))
3 * (2 * 1)
3 * 2
6
[further expansions are left to the reader as an exercise to be
performed OFF list. :) We don't need to know the expansion of
factorial(72) here ;)]
Hopefully that makes it a bit clearer.
C.
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html