`
#include <stdio.h>
int k = 0;
int factorial (int x)
{
if (x == 1)
{
return 1;
}
k = x * factorial (x - 1);
}
int main()
{
printf ("Factorial of %d is: %d\r\n", 5, factorial(5));
return 0;
}
Factorial of 5 is: 120
I have been learning recursion for the last few days, and while working on the factorial of a given number using recursion, everything works fine, but the question I am having is that the above code, without any return statement, is printing the value 120 in the console for the factorial of 5.
Also, I am curious to know how, without any return statement except in the base condition of the factorial function, the recursive call is giving the correct answer.
if (x == 1)
{
return 1;
}
k = x * factorial (x - 1);
As per my understanding, the above line of code would execute like this:
k = 5 * factorial (5-1)
k = 4 * factorial (4-1)
k = 3 * factorial (3-1)
k = 2 * factorial (2-1)
k = 1 * factorial (1-1)
return 1; --> when x is 1
What value it will have in the factorial (x - 1) is something I don't understand. Because this factorial (x) function does not have any return statements.