The other cases recurse toward the base case. This way, the calculation can stop.
e.g. you know the Fibonacci number of 0 and 1. Every other is the sum of the two predecessors. So fib(3) is fib(2)+fib(1); whith fib(2) being fib(1)+fib(0) and fib(1) and fib(0) being known --> the "base case(s)".
public static long sumOfDigits(long n) {
if (n==0) {
return 0;
} else {
return n % 10 + sumOfDigits(n/10);
}
}
The base case returns 0, like the other comment said, this is where the recursion ends. The base case is a final state that you know will inevitably happen. This method here sums the digits in a given number, ie 1 2 3 = 6. Any number less than 10 when divided by 10 will return 0. This lets the function know that it has reached the last digit, and the recursion ends.
30
u/GroundTeaLeaves Jun 16 '21
What is a base case?