Tell us what’s happening:
I’m wondering how the return statement calculates the sum.
return sum(arr, n-1) + arr[n-1];
Thank You
Your code so far
function sum(arr, n) {
// Only change code below this line
if(n <= 0){
return 0;
}else{
return sum(arr, n-1) + arr[n-1];
}
// Only change code above this line
}
// A recursion is the concept that a function can be expressed in terms of itself.
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.
The function call sum(arr, n) returns the sum of the first n elements of the array arr. So, the function call sum(arr, n - 1) returns the sum of the first n - 1 elements of the array arr.
arr[n - 1] is the nth element of the array, so sum(arr, n-1) + arr[n-1] is the sum of the ‘sum of the first n - 1 elements’ and the nth element… Which is the sum of the first n elements.