$ $
A method is “tail recursive” if the recursive call is the last thing that happens.
May be mechanically converted to a while loop.
public static int sum(int[] numbers, int index) {
if (index < 0) {
return 0;
} else {
return numbers[index] + sum(numbers, index - 1);
}
}
private static int sum1(int[] numbers, int index, int accumulator) {
if (index < 0) {
return accumulator;
} else {
accumulator += numbers[index];
return sum1(numbers, index - 1, accumulator);
}
}
private static int sum2(int[] numbers, int index, int accumulator) {
while (true) {
if (index < 0) {
return accumulator;
} else {
accumulator += numbers[index];
index--;
}
}
}
Space, Right Arrow or swipe left to move to next slide, click help below for more details