Loop recursion in functions and understanding the algorithm

Tell us what’s happening:
Describe your issue in detail here.

I'm trying to wrap my head around the Algorithm that makes this work. I'm having a hard time. While I can write it based on he example, I'm not understanding exactly how it's working. Is it using n var as a way to cycle through the positions in an array? In other words like an if statement going through 0, 1, 2 and then it stops when it hits the if statement because that's how you get out of the loop? Also, why return 1 or 0 or whatever. Why not just return;

**Your code so far**

function sum(arr, n) {
  // Only change code below this line
  if (n <= 0) {
      return 0;
    } else {
      return sum(arr, n - 1) + arr[n - 1];
    }
  // 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/92.0.4515.131 Safari/537.36

Challenge: Replace Loops using Recursion

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

This is not a loop, so don’t get tricked into thinking about loops here.

It is important to realize that sum() always returns a number. We are using this fact to make the work that this functions does smaller.

In the base case, we establish what happens if we ask our function the smallest problem we can: “sum 0 elements from this array together”
This gives us a smallest easy problem that we can solve so that we don’t recurse forever.

In the recursive case, we call the function with a slightly smaller (easier) version of the problem. We compute the sum of the first n - 1 elements. Then we use this number to compute the sum of the first n elements by adding the nth element to our sum and returning this number.

function sum(arr, n) {
 // Only change code below this line
 if (n <= 0) {
   let sumOfNothing = 0;
   return sumOfNothing;
 } else {
   let sumOfFirstPart = sum(arr, n - 1);
   let lastElement = arr[n - 1];
   return sumOfFirstPart + lastElement;
 }
 // Only change code above this line
}
1 Like

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