The Curse Of Recursion

Tell us what’s happening:
Describe your issue in detail here.
Could someone please take a movement to explain more deeply and simplify recursion to me?

Thank you.

  **Your code so far**

function sum(arr, n) {
// Only change code below this line

// Only change code above this line
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36

Challenge: Replace Loops using Recursion

Link to the challenge:

It looks like you haven’t done anything on this challenge yet, so I’ll talk about the example.

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

The idea with recursion is to write the problem in terms of itself.

In this case, multiply(arr, n) is a function that takes an array arr and a number n and returns the product of the first n elements of arr.

Well, the product of the first n elements (say the first 5 elements) is the product of the first n - 1 elements (the first 4 elements) multiplied by the nth element (the 5th element).

So multiply(arr, n) === multiply(arr, n - 1) * arr[n - 1].

But at some point we have to stop. For this example, the ‘base case’ is the simplest version of the problem. When n <= 0, then we say that our product is 1.

1 Like

Emm :confused: hmm… okie

Body is too short (minimum is 20 characters)Body is too short (minimum is 20 characters) {jezz i don’t have much to say}

do you still have questions? we are unable to know if something was useful, or you need more explanations if you don’t say anything

1 Like

The concept of recursion I get it. It calls itself until the condition meets and then stops which is called “base case”. However, the above code line is still a little tricky for me to understand :sweat_smile:

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