So I was reading a article on Recursion. I understand the math, but how does this run multiple times inside the function without having a loop? I’ve always known functions to run once unless otherwise specified. But this function in this case runs 5 times before it stops?
function factorial(n)
if n <= 1 then -- base case
return 1
else
return n * factorial(n-1) -- recursive step
end
end
print(factorial(6),"fact")
When the code that runs through factorial(n-1), the entire function gets gone through again. This causes the code to “repeat” itself without a loop. Because of the base case, the code is limited to running a total of (n-1) times before it stops. This gets the factorial by returning the factorial of the number less than n.
To try an explain it myself, when the conditional check is performed “n <= 1” if when evaluated a Boolean value of true results (which would indicate n is equal to or less than 1 a number of 1 value is returned to the point at which the function was called. Otherwise if n is greater than 1 a return statement is executed which multiplies the current value of n with the value returned by calling the defined function named “factorial” (this is where the recursion occurs) and passing the current value of n with 1 subtracted from it as an argument to the function. Whenever a function is called its returned value(s) are returned to the exact point at which the function was called, so here when the recursion ends the final value is returned and subsequently passed as an argument to the print call, when the recursion is ongoing those returned values are being returned at the end of the return statement of the function named “factorial”.