0

I have trouble understanding the code of this recursive function. I am new to DART programming. I understand what a recursive function accomplishes, but I have a problem understanding the programming syntax.

int sum(List<int> numberList, int index) {
  if (index < 0) {
    return 0;
  } else {
    return numberList[index] + sum(numberList, index - 1);
  }
}

main() {
  // Driver Code
  var result = sum([1, 2, 3, 4, 5], 4);
  print(result);
}

Question: where is the value for each step stored- Does the result for the first pass at line 5 equals 9 taken the inputs from line 11. Where is the value of result 9 stored? How does the function know to add 9 + 3 in the second pass?

Does the recursive function have "internal memory" of the values generated by each pass?

My understanding of the programing language would be that var result passes the arguments to the sum function.

The sum function executes the if-else command until the index value is 0, which means it executes 4 times. With the first pass, the return command creates a value of 9 (5 + 4 since the value of the index is 5 and the value of index-1 is 4).

Here begins my confusion. The sum function would now do a second if-else pass and execute the return command again.

Now the initial value of numberList[index] would need to be 9 and the value of sum(numberList, index - 1); would need to be 3, to get 9 + 3 = 12. Additional 2 passes gets 12 + 2 = 14 and 14 + 1 = 15 the expected result.

My question here is how does (if it does) the index value in the "numberList[index]" changes. The index value is defined as 4 which corresponds to value 5 in the List. Is this an internal logic of the recursive function or am I completely misinterpreting the programming syntax? I would expect that we have a "temporary" variable for the result which increases with each pass.

Thanks.

0 Answers0