Question regarding Replace Loops using Recursion

I knew that recursion is like the concept of factorial in mathematics, but I still have a question about the calculation outcome, if I apply sum([2, 3, 4, 5], 3), isn’t that should be 10?
((sum([2, 3, 4, 5], **2**)) + **4** + (sum([2, 3, 4, 5], **1**)) + **3**) + **0** → 2 + 4 + 1 + 3 + 0 = 10

But why the outcome is 9?
Here is the code:

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

Where are the extra values coming from?

sum([2, 3, 4, 5], 3) says "sum the first 3 elements of the array [2, 3, 4, 5].

So,
sum([2, 3, 4, 5], 3) returns sum([2, 3, 4, 5], 2) + [2, 3, 4, 5][2] == sum([2, 3, 4, 5], 2) + 4

We need the value of sum([2, 3, 4, 5], 2)

sum([2, 3, 4, 5], 2) returns sum([2, 3, 4, 5], 1) + [2, 3, 4, 5][1] == sum([2, 3, 4, 5], 1) + 3

We need the value of sum([2, 3, 4, 5], 1)

sum([2, 3, 4, 5], 1) returns sum([2, 3, 4, 5], 0) + [2, 3, 4, 5][0] == sum([2, 3, 4, 5], 0) + 2

We need the value of sum([2, 3, 4, 5], 0)

sum([2, 3, 4, 5], 2) returns 0

Thus, sum([2, 3, 4, 5], 1) returns sum([2, 3, 4, 5], 0) + [2, 3, 4, 5][0] == sum([2, 3, 4, 5], 0) + 2 == 0 + 2 == 2

Thus, sum([2, 3, 4, 5], 2) returns sum([2, 3, 4, 5], 1) + [2, 3, 4, 5][1] == sum([2, 3, 4, 5], 1) + 3 == 2 + 3 == 5

Thus, sum([2, 3, 4, 5], 3) returns sum([2, 3, 4, 5], 2) + [2, 3, 4, 5][2] == sum([2, 3, 4, 5], 2) + 4 == 5 + 4 == 9

sum([2, 3, 4, 5], 3) returns 9

1 Like

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 (’).

1 Like

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