Break down the stack for this recursion

Can someone break down the stack for the following code? How is it calculating? What is happening inside the parenthesis?

I understand that arr[n-1] is calling the element from array by index value, and multiply it with the function. However what does the first ‘n’ inside the parenthesis stand for? And what is happening between the ‘arr’ and the first ‘n-1’ inside parenthesis? Are they multiplying?

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

Let’s say the array is [1,2,3,4,5,6] and we call multiply(arr, 5)
Until n is 0, it will call itself with multiply(arr, 4), then multiply(arr, 3) …

multiply(arr, 0) returns 1
multiply(arr, 1) multiplies that 1 with arr[0] and returns 1
multiply(arr,2) multiplies that 1 with arr[1] (which is 2) and returns 2

multiply(arr, 5) therefore has to multiply 1 * arr[0] * … * arr[4] = 1 * 1 * 2 * 3 * 4 * 5 = 120

1 Like

multiply(arr, n - 1) * arr[n - 1] will give the product of the value returned by multiply(arr, n - 1) and the value of arr[n - 1] element.

n ’ is the variable we pass to the function as an argument( function multiply(arr, n) {...} ). Whereever you find it within the function body, it refers to that value. n-1 would give us that value subtracted by 1.

You are asking what is happening between arr and n-1 by calling multiply(arr, n - 1) . You can determine that by looking at the multiply function body. There you can see how the arguments are used to return a value.

1 Like

Thank you so much for your response. This is really helpful.

This is really helpful. Thank you so much for your response.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.