Good evening friends

Please do anyone has a solid of understanding of recursive functions.

I just can’t figure what is happening in the background with the recursive functions.

for example

function multiply(arr, n) {

if (n <= 0) {

return 1

} else {

return multiply (arr, n - 1) * arr[n - 1]

}

}

I understand the condition but I don’t quite understand what is happening in the rest part of the code.

Please, someone, help throw more light on this for me

Recursion is a complicated topic. Basically, you have a function that calls itself - but each time it does, it’s a new occurrence of itself, with no knowledge of anything but what it’s been fed via variables.

In this particular case, we start the first recursive call with a complete array and how many elements in that array we want to multiply together. Say our array was `[2,4,5,7,9]`

and `n=3`

, we only want to multiply the first three elements.

So first pass, we have the full array and an n value of 3. Arrays are zero indexed, but that three is a one-based count. So we need to find the array element at index position `n-1`

(3-1), or `arr[2]`

and multiply it by the returned value of our recursive call. The parameters we pass into our function decrease n by one, moving closer to the start of the array, and that full array.

Second pass, same array, but `n=2`

. So we’ll eventually return the value of `arr[n-1] * <the recursive call>`

.

“Eventually” being when `n=0`

, and we end the recursion by returning one to the next layer out, which returns `1*arr[0]`

to the function that called it. The calling function takes that value and multiplies it by it’s value: `(1*arr[0]) * arr[1]`

.

This continues until we reach the penis call of our recursive function.

A clearer explanation of the logic, and of how we think recursively often, can be found at https://tobycodes.tech/posts/recursion-all-the-way-down

2 Likes

Hey @OnazOnaz!

Colt Steele has some great videos on recursion and call stacks.

Hope this helps!

Happy coding!

2 Likes