I have so many questions here I don’t know where to start. I should say that I have done all the exercises up to this point but otherwise have had absolutely no experience with coding. Therefore it is entirely possible, in fact likely, that despite my best efforts I have not understood everything fully up to this point.
OK so let me try and explain where I am. I have managed to get the correct solution without understanding anything (which is often possible on this site). So I am not trying to find the solution but seeking a level of understanding.
Line 1 // function sum(arr, n) { // sets up a function and names it ‘sum’. It gives it two parameters. One is an array to be filled with number elements. The other is how many number elements in the array (starting from the left) we wish to add together.
Question 1 - is ‘arr’ a special keyword or could anything be written here - like “numberList” for example? I’m assuming any name could be used.
Line 2 / 3 // if (n <= 0) { return n; // This sets up the ‘base case’ which is the eventual exit out of the recursive state. This is the point at which there are ‘no / no more’ numbers in the array.
Question 2 - Why does it return ‘n’? ‘n’ is just the number of elements you state to be added together. Why does it not just return ‘0’?
So then we have the ‘recursive case’
Line 5 // return sum (arr, n - 1) + arr[n-1]; // I have no idea what this means. I have read an extremely long thread on this and got something out of it but not a full understanding. I know that an array indexing starts at ‘0’ instead of ‘1’. That must be why the ‘n’ becomes ‘n - 1’.
Question 3 - What does sum (arr, n - 1) tell the computer?
Question 4 - Is ‘sum’ a special keyword so the computer knows to add all the numbers in the array? I don’t remember coming across this.
Question 5 - Does ‘n’ refer to the index number as the recursive function keeps calling itself? So it would count down until it reaches zero.
Question 6 - What is the difference between (arr, n -1) and arr[n - 1]? The second one refers to a specific element in the array, but what does the first one mean?
Essentially I don’t understand what is actually happening in a recursive function. I get that it keeps calling itself until a return statement it met, but so does a loop have exit criteria.
Any help would be really appreciated because I’m beginning to struggle here.
Your code so far
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return n;
} else {
return sum (arr, n - 1) + arr[n-1];
}
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge: