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: