What am I doing wrong in this recursion?

Tell us what’s happening:
First of all, n-1 is supposed to be added to n and then n-2 with the sum and so on. So in pesudocode, basically if n =4, it will add 4+function(3), and then 4+3+function(2) and so on until it hits the base case. So why the solution says we need to add n-1 with function(n-1) ?

Also array[num] is used to index the array data. n might be the length of an array, not index value of the last data. So why we are using array[n]?
What am I missing here? Please explain. Thank you.

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

You shouldn’t be using arr[n]. On the first function call, arr[n] is past the end of the array and will be undefined.

Zero based indexing means the indices go from 0 to length - 1.

1 Like

Right, so it should be like return arr[n - 1] + sum(arr, n - 2); isn’t it?
I’m sorry I’m new in this.

Close, you still want sum(arr, n - 1).

// Describing length
sum(arr, lengthOfArr);

// Indexing based on length
arr[lengthOfArr - 1]

// Indexing based on length
arr[lengthOfArr - 1] Right so we got the index of last entry of the array. Now we should add the previous one lengthOfArr - 2 to this one right? That should be the first else condition… no? I understood that we have to process sum(arr, lengthOfArr -1) as well… But here everything is getting confusing :exploding_head:

This sum function is based on recursion. In recursion, we want to solve the current problem by relating the current problem to a smaller or ‘reduced’ problem.

Let’s look at a specific example:

// Setup
let arr = [1, 2, 4, 9];
let n = arr.length;

// Index into last element
currentValue = arr[n - 1];

// Sum of first part
let reducedArraySum = 7; // How can I compute this???

// Add together
let arrSum = reducedArraySum + currentValue;
console.log(arrSum === 16);

So, we can write your function more verbosely

function sum(arr, n) {
  // Only change code below this line
  if ( n <= 0) {
    return 0;
  } else {
    let currentValue = ???; // What goes here? What is the current last element?
    let reducedArraySum = ???; // What goes here? What is the sum of the first part of the array?
    return reducedArraySum + currentValue;
  }
  // Only change code above this line
}
1 Like

Thank you for keeping patience with me. It’s 95% clear now.
Except this part:

// Sum of first part
let reducedArraySum = 7; // How can I compute this???

Yes how?
I can think of a ‘for loop’, assuming we don’t know what are in the array. :thinking:
But I’m not sure

var reducedArraySum = 0;
for (var i = 0; i <= arr.length; i++) {
reducedArraySum += arr[i];
}

You want to add the first n - 1 elements of the array together. Do you have a function that does that for you?

No…?
I can use the ‘for of’ loop to add all numbers though

var reducedArraySum = 0;
for (var i of arr) {
reducedArraySum += i;
}

We didn’t learn about for of and reduce method (I looked up for ways to sum numbers in an array, and I found these two used most).

The instructions say:

Write a recursive function, sum(arr, n) , that returns the sum of the first n elements of an array arr .

This is where the recursion occurs. sum(arr, 1) returns the sum of the first 1 elements. sum(arr, 2) returns the sum of the first 2 elements. sum(arr, 3) returns the sum of the first 3 elements.

How would you find the sum of the first n - 1 elements?

Hi,
i will try to explain maybe on how i can read it hope will be helpful as well, and hope this is more clear, also maybe @JeremyLT can help us validate this since you have more experience from both of us.

function sum(arr, n) {
  // Only change code below this line
  if( n <= 0 ){  
  // n in this case is 3 if its true meaning equal and small than 0 then
  // will return false. meaning 0. (this is your base case).
    return 0;
  }
    /* 
      if does not meet the criteria above will call the function itself 
      and will return the function of sum(arr, n-1). witch is the
      first element of the array.
      In addition this line of code arr[n-1]; will do the following work.
      Lets have this in consideration Example code:
     
      n = 3
      array = [2,3,4];
      function: sum([2,3,4], 3);

    */
    return sum(arr, n - 1) + arr[n - 1]; 
    /* 
      3 is the n put it in this code line arr[3 - 1]; = arr[2] now this 
      is the array base index, witch is 4 in the array.
    */ 

    // then we have this arr[2] = 4
    //  (arr, 3) =  +  arr[2] = 4
    //  (arr, 2) =  +  arr[1] = 3
    //  (arr, 1) =  +  arr[0] = 2 
    // 4 + 3 + 2 = 9 
   
  // Only change code above this line
}
  var result = sum([2,3,4], 3); //
  console.log(result); // Output: 9