I want to know how does this program make results in simple way

Tell us what’s happening:

  **Your code so far**

function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
// Only change code above this line
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

1 Like

I’m not sure I understand your question. You have pasted in the correct answer for the challenge. Do you understand the code you pasted above?

1 Like

I do not understand it

1 Like

Recursion has been discussed so many times in this forum that I’m not exactly excited to type out a long explanation here :slight_smile: Search for “recursion” using the search icon at the top of the forums here and you will find a ton of links to previous discussions about recursion.

But maybe someone else will feel differently and type something up here?

1 Like

FireShot Capture 014 - I want to know how does this program make results in simple way - Jav_ - forum.freecodecamp.org

1 Like

Explain to us what is going on in this return statement. Let’s use the following as an example. You initially call the function as:

sum([0, 1, 2], 3);

What will that return statement look like (fill in the actual values)?

1 Like

I want to know what does this function do with this elements

1 Like

And I am trying to help you understand this by leading you through how the function works. So if we start with the initial function call of

sum([0, 1, 2], 3);

We will hit the else statement and thus do the following:

return sum(arr, n - 1) + arr[n - 1];

Replace all the variables in that return statement with the actual values.

1 Like

I am trying to understand what is the different between the add sign and the miltiply sign

1 Like

+ adds two things together, usually numbers (2 + 2 = 4), but in JS it can also concatenate strings ("a" + "b" = "ab").

* multiplies two numbers (2 * 3 = 6).

I’m not sure if this is what you were asking or if you meant something else?

1 Like

I mean the sign in ```
return multiply(arr, n - 1) * arr[n - 1];

addition
return sum(arr, n - 1) + arr[n - 1];
1 Like

The addition sign in this return statement adds two numbers. Using my example above, what is the value of arr[n-1]? And then you are adding that value to what is returned by the function call sum(arr, n - 1). Again, using my example above, fill in the actual values for the return statement in the else block when you call it for the first time.

1 Like

thinks you for spending time to help me

1 Like

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