Can someone explain to me what is the details of line 5 return numberList[index] + sum(numberList, index - 1);

Viewed 59

Can someone explain the syntax process? How line 5 will be implemented and what is the sequence for these three elements and what is the value each time in the dart code snippet below?

  1. numberList[index]
  2. sum(numberList,
  3. index - 1);
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);
}
1 Answers

I will try to show the sequence for these elements, when the code is executed, in the following image (click on the image to see it in correct size):

execution

As you can see, when the last call "returns 0" the response of the sum calls are returning the result and propagating to the left.

I hope this help you

Edited:

I've added the following image, to show how the result is being returned until the first call of sum.

enter image description here

Related