matt
matt

Reputation: 285

Recursive function- keeps returning 0?

Im trying to write a recursive function which returns the factorial of a number. If the number is 0 or negative then it should return 0. However everytime i test it, it always returns 0, can anyone shed some light on this please?

int factorial( int integer)
{
    if( integer <= 0)
    {
        return 0;
    }

    else

        return integer* (factorial(integer-1));

} 

Upvotes: 2

Views: 1472

Answers (7)

calebds
calebds

Reputation: 26228

You will always multiply the result by zero in your base case. Factorial of 0 is 1, not 0.

If the function must return 0 when the input is less than 1:

int factorial (int integer) {
    if (integer < 1) {
        return 0;
    } else if (integer == 1) {
        return 1;
    } else {
        return integer * factorial(integer-1);
    }
}

Not the shortest implementation, but quite readable.

Upvotes: 4

theglauber
theglauber

Reputation: 29595

As it keeps calling itself with integer - 1, it will eventually call itself with 0, and then you will have a call like this:

return integer * (factorial(0))

which will resolve to

return integer * 0

which is 0

Upvotes: 4

Masa
Masa

Reputation: 311

You are allowing the integer to go up to zero through recursive calls and returning zero when it finds integer is zero. So you are multiplying your result in last recursive call by zero. Thus you are always getting a zero as answer.

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168596

Try to execute a simple test case with pencil and paper:

main:
  factorial(3)
    return 3 * factorial(2)
      factorial(2)
        return 2 * factorial(1)
          factorial(1)
            return 1 * factorial(0)
              factorial(0)
                return 0
            return 1 * 0 (equals 0)
        return 2 * 0 (equals 0)
   return 3 * 0 (equals 0)

So, it appears that every recursive invocation reaches "0".

Try adding this condition:

else if(integer == 1)
  return 1;

Upvotes: 2

Sergio
Sergio

Reputation: 681

Simply use 1 instead of 0. When you use 0 any number you have will be multiplied by 0, returning 0.

Example:

5! = 5.4.3.2.1 = 120 and not 5.4.3.2.1.0 = 0

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

Your function must return 1 in the base case, like this:

if (integer <= 0) {
    return 1;
}

You're multiplying numbers and as you know any number multiplied by 0 is zero. What you need to use instead is 1, the multiplicative identity, since any number multiplied by one is the number itself.

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

You must return 1, multiplying by 0 always returns 0:

if( integer < 2)
{
    return 1;
}

Upvotes: 0

Related Questions