I have a hard time wrapping my head around recursion too.
What’s happening is that it passes in:
[1, 2, 3, 4, 5]
and n == 3.
Because N > 0, it goes to the ELSE, which calls multiply again with n -1
So it continues until it gets to n = 0, and it returns 1 to the version of multiply which called that.
So, we get the else call that says:
return {1} * arr[n-1].
In this case we know that the n == 1 since that was the value that must have been in play when it called multiply with n == 0. Since n == 1, we have return {1} * arr[0], which is also one. We return 1 to the multiply call when n == 2.
So now we have
return {1} * arr[2-1], == 2.
And now we go up another step to:
return {2} * arr[3-1] == 6.
And since that was the initial n value, you get six.
There are a lot of posts on recursion. Please try out the search function. On this particular function, I’ve given a detailed explanations here , among other places.
Recursion is a very confusing topic, especially for beginners. It takes a while to wrap your head around it.
I was right there with you just like two weeks ago. I recommend going to leetcode and doing some recursion practice problems. That’s what I did. I still can’t knock them out immediately, but I can now knock out the medium-difficulty ones with a bit of debugging and tinkering.