Functional Recursions

Tell us what’s happening:

Hi guys,

I do have a question, i have read the instructions, about a recursive function. A function that calls itself.

However, i dont really know how this works,

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

Can anyone explain the parameters?

And, what exactly is passed to the array? There is no array here (yet).

What is the “n”?
////////////////////////////////////////////////////////////
What i read is the following:
function sum(arr, n) {
// function called sum, has two parameters: “arr,” “n”
if(n <= 0) {
//if n is smaller and equal to zero
return 0;
//return 0
} else {
// else
return sum(arr, n - 1) + arr[n - 1];
//return sum (arr "n"minus one) + arr [n minus 1]?

/*
QUESTION
It really is this last line, what i think is too abstract. What does it imply, what does arr mean (there is no array here) and n minus one?, so the number is above 1, but how do we know what number it really is?
*/

}
}

Your code so far


// function sum(arr, n) {
//   // Only change code below this line

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

Your browser information:

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

Challenge: Replace Loops using Recursion

Link to the challenge:

Walk through it with a small number. arr is an unknown array. n is the length of the array arr. so if I’m calling sum([3,5,7,9],4), I’m going to sum up all the numbers [3,5,7,9], which is 24.
So the computer is going to go:
sum([3,5,7,9],3) + arr[3]
sum([3,5,7,9],2) + arr[2]
sum([3,5,7,9],1) + arr[1]
sum([3,5,7,9],0) + arr[0] // it stops here because n is zero and returns zero
return 0 + arr[0] // arr[0] is 3, so returns 0 + 3 which is 3
return 3 + arr[1] // arr[1] is 5, so return 3 + 5 which is 8
return 8 + arr[2] // arr[2] is 7, so return 8 + 7 which is 15
return 15 + arr[3] // arr[3] is 9, so return 15 + 9 which is 24

2 Likes