-1

I am new to programming and I found myself stuck in this concept. I just find it very confusing. Can someone enlighten me on how this code is supposed to work?

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

Thanks! and sorry if this is so noob of me to ask peace!

  • Does this answer your question? [Understanding recursion](https://stackoverflow.com/questions/717725/understanding-recursion) – ralismark Mar 08 '20 at 12:15

1 Answers1

0

In recursions you call your function in your function until a given requirement is fulfilled.

In this case, your function requires an array as input and the given index where to start (normally this should be the length of the array - 1).

F.e. call the function sum([1,2,3,4], 3).

It checks if your index is at position 0, which is not the case. Then it adds the item at the given index arr[3] = 4 to the same function, but with an index 1 lower: sum([1,2,3,4], 3) = sum([1,2,3,4], 2) + 4

The next function adds its index arr[2] = 3 to the sum to the same function of index 1: sum([1,2,3,4], 2) = sum([1,2,3,4], 1) + 3. If you fill this in your first function call it becomes: sum([1,2,3,4], 3) = sum([1,2,3,4], 1) + 3 + 4

The next function adds its index arr[1] = 2 to the sum to the same function of index 0: sum([1,2,3,4], 1) = sum([1,2,3,4], 0) + 2. If you fill this in your first function call it becomes: sum([1,2,3,4], 3) = sum([1,2,3,4], 0) + 2 + 3 + 4

In this case of n = 0, it returns just the value of the array at index 0. value of the array in that index: sum([1,2,3,4], 0) = arr[0] = 1

So the total function adds up tosum([1,2,3,4], 3) = arr[0] + arr[1] + arr[2] + arr[3] = 1 + 2 + 3 + 4 = 10

Daan Seuntjens
  • 880
  • 1
  • 18
  • 37