Just confused on this Problem (Recursion)

Honestly just wondering how this:

Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first n elements of an array to create the product of those elements. Using a for loop, you could do this:

  function multiply(arr, n) {
    var product = 1;
    for (var i = 0; i < n; i++) {
        product *= arr[i];
    }
    return product;
  }

Is true to be this:

However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]. That means you can rewrite multiply in terms of itself and never need to use a loop.

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

The recursive version of multiply breaks down like this. In the base case, where n <= 0, it returns 1. For larger values of n, it calls itself, but with n - 1. That function call is evaluated in the same way, calling multiply again until n <= 0. At this point, all the functions can return and the original multiply returns the answer.

I assume it is returning 1 because they want that to be false within that condition, but where is the -1 coming from? I do not see anything to do with -1 in the non-recursion solution. Overall, I’m just really confused on what is happening here. I don’t like figuring out the solution to something but not having a clue on what’s going on.

i don’t think it ever returns a 1. what they meant by the -1 was that it reduced its value by removing 1 from the previous value until it is less than or equal to 0

// this function multiplies the numbers in an array it takes two values 
  function multiply(arr, n) {
/**the below if statement checks to make sure that the n value does not depreciate below 0  once it gets to 0 it returns a 1 **/   
if (n <= 0) {
      return 1;
    } else {
  
      return multiply(arr, n - 1) * arr[n - 1];
  
    }
  }

/** imagine an array of three numbers [1,2,3] called three. what the return statement does is to multiply the first the first value three[2] then the second three[1] then the third[0] . immediately it gets to a 0 it returns a 1. as seen in that return statement it besomes 321.
please take note that the first piece multiply(arr, n-1) does the job of reducing the n value until it becomes 0.

1 Like

Ahhh I understand now. Thank you