Search code examples
javascriptarraysfor-looprecursionsum

How to sum first n number of entries in an array?


I'm new to programming and learning about javascript recursion. It's my 5th day with JavaScript and following an online course. The problem is that I need to sum up first n numbers of entries (first 3 numbers in this case) in an array. But I'm ending up with sum of all and that also I'm not sure about.

var theArray = [1, 3, 8, 5, 7];

function sum(arr, n) {
  if (n <= 0) {
    return 1;
  } else {
    return arr[n - 1] + sum(arr, n - 2);
    //assuming n is arr.length and n-1 is hence arr.length-1
  }
}

console.log(sum(theArray, 3));

What am I doing wrong? I checked most people are solving such with reduce method or with for of loop. I didn't learn those yet in the curriculum. But I know 'for loop' but that's good if the numbers are in incremental order I guess. Please explain this problem in my level.


Solution

  • When implementing something recursively, it's a good idea to think about the base condition. It does look like that's where you started, but your logic is flawed. n is the number of elements you would like to sum together. So let's say you want to sum the first n=3 elements of the array [2,3,4,5,6] and get 9. Here are the iterations.

    1. return arr[n-1] + sum(arr, n-1) // arr[2] + sum(arr, 2) === 4 + sum(arr, 2) === 4 + 5
    2. return arr[n-1] + sum(arr, n-1) // arr[1] + sum(arr, 1) === 3 + sum(arr, 2) === 3 + 2
    3. return arr[n-1] // arr[0] === 2 (base case when n is 1)

    I didn't solve the problem for you since this is obviously a school exercise, but the point is that the base case and the recursive call that you have are both slightly off.