I made a recursive function in C++ to get a factorial.
unsigned factorial(unsigned n, int j = 1) {
j++;
if(j < n) {
return j * factorial(n, j);
}
return n;
}
It works. However, if i remove the return n;
the function still working and i don't know why.
For simplicity, i got a control flow of factorial(5) with return n;
removed, that is the following:
factorial (5,1) returns 2 * factorial (5,2)
factorial (5,2) returns 3 * factorial (5,3)
factorial (5,3) returns 3 * factorial (5,4)
And in the last, i.e factorial(5,4) since in the condition if(j < n)
, j = 5 and n = 5, the condition not satisfies and therefore factorial(5,4) must return 1 by default. Thus, the total recursive function must return 2 * 3 * 4 * factorial(5,4) = 2 * 3 * 4 * 1 = 4! and not 5!.
Thanks in advance.