-1

We know that factorial could be written as (if use C++)

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

if wrote as

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

See there's no return in the else bracket, then whatever the number is, the result is always 1, why is that?

Thank you very much.

Lei
  • 1
  • 1
  • 2
    if the language in question is C, then the bottom function will exhibit undefined behavior as the `else` path never returns anything; in Java, the code will fail to compile entirely for the same reason – obataku Aug 08 '16 at 03:27
  • And whatever the language in your question may be, you should have identified it via tags or in your question. – user207421 Aug 08 '16 at 10:23

1 Answers1

-1

For finding out the Factorial of any number, what we do it multiply the number with 1 less increment until it reaches 1

For example To find out factorial of n : we do n*(n-1)* (n-2) ...(n-m) until (n-m) =1

Consider your code and try to make a stack and a dry run of the code.

On first call, return is 5*fac(5-1) .. Consequetively it goes on until its

5*4*3*2*fact(1) where the fac(1) returns 1 can everything is traced to previous calls.

The short answer is the return 1 acts as a base condition which is the stopping point.

Sohil
  • 532
  • 7
  • 26
  • To be more precise to the question you are asking: There is no return in the else block . Hence the return will be 1 once it hits the base condition. Once the code proceeds towards the recursion. Your code just calculates the else block but doesnot return to the called function. Hence the end return is always 1. – Sohil Aug 08 '16 at 08:12
  • How, *exactly,* does falling through the `else` block cause the method to return 1? This is the actual question, and you haven't answered it. – user207421 Aug 08 '16 at 10:22
  • Here's a [link](http://stackoverflow.com/questions/5631447/how-recursion-works-in-c) to better understand the problem Any recursion will maintain an internal stack to track all the necessary instance of the variables when being called. Notice that your function must return an int value. there is only one return statement in the code which is called when factorial(0). This is considered from return stack while returning to the called function – Sohil Aug 08 '16 at 11:26