# I Need Help with Recursion

Tell us what’s happening:
I was wondering what the code is doing here: multiply(arr, n - 1 ) * arr[n - 1];

``````
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
``````

User Agent is: `Mozilla/5.0 (X11; CrOS x86_64 13020.87.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.119 Safari/537.36`.

Challenge: Replace Loops using Recursion

Link to the challenge:

The function is calling itself (the recursive step) until it reaches the base case (return 1 if n<= 0) and multiplying the results of all the function calls together.
An Example: If n = 5 and arr = [2,3,4,5,6] then the return statement would do the following

``````return multiply(arr, n - 1) * arr[n - 1]
return arr[5-1] * arr[4-1] * arr[3-1] * arr[2-1] *arr[1-1] * 1)
return 6*5*4*3*2*1
``````

for addition the return statement would be something like

``````return add(arr, n - 1) + arr[n - 1]
return  arr[5-1] + arr[4-1] + arr[3-1] + arr[2-1] + arr[1-1] + 0
return  6+5+4+3+2+0
``````

notice the base case is different for the addition example, we dont want to add an extra 1

you can also look at Using recursive!

1 Like