so if we call factorial(3),
we get to line 5 and calculate outputValue = 3(factorial(2)),
so if we call factorial(2),
we get to line 5 and calculate outputValue_2 = 2(factorial(1)).
factorial(1) returns 1, so in our second call to factorial(2), outputValue_2 = 2(1) = 2
that returns to our first call to factorial(3) and we get outputValue = 3(2) = 6
so we return 6, which we now know is 3!
Hope this helps and let me know if you have any questions.
Definition: a function is recursive if it calls itself.
That's only direct recursion, you can also have indirect recursion if the function calls another function which then calls the original. This is used lots when evaluating expressions or any operations with order of precedence.
Recursion is simpler than you're making it. Definition: a function is recursive if it calls itself.
As an example, let's write a function in python to calculate z!=z(z-1)(z-2)*...*1
def factorial(z): if (n<=1): return 1 else: outputValue = z*factorial(z-1) return outputValue
so if we call factorial(3), we get to line 5 and calculate outputValue = 3(factorial(2)), so if we call factorial(2), we get to line 5 and calculate outputValue_2 = 2(factorial(1)). factorial(1) returns 1, so in our second call to factorial(2), outputValue_2 = 2(1) = 2 that returns to our first call to factorial(3) and we get outputValue = 3(2) = 6 so we return 6, which we now know is 3!
Hope this helps and let me know if you have any questions.
That's only direct recursion, you can also have indirect recursion if the function calls another function which then calls the original. This is used lots when evaluating expressions or any operations with order of precedence.
Sure