Returning 0 versus returning 1

Jul 4, 2012 at 10:55pm
I am working on some recursion problems, and I have a question about returning a 0 versus a 1. The book shows this function, which I suppose is a factorial function, only when I run it, I get a 0 for the answer. When I changed the return statement from a "return 0" to a "return 1" I got the correct answer - 120. (n = 5)
1
2
3
4
5
6
7
unsigned F(unsigned n)
{
    if (n == 0)
        return 1;
    // else
    return n * F(n-1);
}


Why does the book have return 0? Obviously, this is something I should understand by now, but I don't, so I need some guidance. Am I incorrect in assuming it is supposed to return 120? With the above function written with a " return 0" won't 0 always be the answer? So, would you say that what is calculated is the factorial of n, assuming that the return should return 1? Or am I missing something here?
Jul 4, 2012 at 10:59pm
You are correct; the return value should be 1.

As you stated, when called you will eventually recurse down to n = 0 and return 0, which will cause all the multiplication to end up being 0.
Jul 4, 2012 at 11:04pm
Oh good, thank god. At least I'm not a complete retard. Programming is hard. Harder still when your damn book is wrong!
Jul 4, 2012 at 11:07pm
The result of the function is: (Return Value under the If Statement) ^ (n+1).
So if you put "return 1" it's 1^(n+1), which is always equal to 1.

EDIT: Wrong, leave it.
Last edited on Jul 4, 2012 at 11:31pm
Jul 4, 2012 at 11:13pm
The result of the function is: (Return Value under the If Statement) ^ (n+1).
So if you put "return 1" it's 1^(n+1), which is always equal to 1.


It's not. It's a factorial function, like OP stated.

Called with n it goes:

n * F(n-1)
n * (n-1 * F(n-2))
...
n * (n-1 * (... * (0))...)


You don't want the zero at the end.
Jul 4, 2012 at 11:31pm
Right, I didn't take much looks at the "return n * F(n-1)" part. Thanks for the correction.
Topic archived. No new replies allowed.