Trying to Learn Recursion

Hey, guys can some please try and explain recursion to me, please.

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

can someone tell me what this out puts to, so I came better understand this topic

Say arr is [1,2,3]. And say n is 3

If n is 0, then it returns 1, regardless: the if block is run. This is the base, start here. So multiply([1,2,3], 0) is 1.

So if n is 1, then it is greater than 0. So the else block is run.

It is multiply(arr, n - 1) * arr[n - 1];. So that is multiply([1,2,3], 0) * 1;. You know that if n is 0, the value is 1, so that is 1 * 1, so it’s 1.

So if n is 2, then it is greater than 0. So the else block is run.

It is multiply(arr, n - 1) * arr[n - 1];. So that is multiply([1,2,3], 1) * 2;. You know that if n is 1, the value is 1, so that is 1 * 2, so it’s 2.

So if n is 3, then it is greater than 0. So the else block is run.

It is multiply(arr, n - 1) * arr[n - 1];. So that is multiply([1,2,3], 2) * 3;. You know that if n is 2, the value is 2, so that is 2 * 3, so it’s 6.

Now you’re finished. The answer is 6.

1 Like

You can convert the code to iteration. like the blow code.

function iter(arr, n) {
  let ret = 1
  
  while(n > 0) {
    ret = ret * arr[n - 1]
    n = n - 1
  }
  
  return ret
}

Hope it can help you!

1 Like