AP Computer Science Exam Question:
Write a base case for a recursive function sumDigits(int n)
that takes an integer n
as input and returns the sum of its digits.
Answer:
The base case for the recursive function sumDigits(int n)
can be defined as follows:
public static int sumDigits(int n) {
if (n == 0) { // Base case: If the integer is 0
return 0; // Return 0 as the sum of its digits
}
}
Explanation:
sumDigits(int n)
function is checked using the conditional statement if (n == 0)
.n
is equal to 0, the function immediately returns 0 as the sum of its digits.
n
is 0, it means there are no remaining digits to sum, so the sum is 0.sumDigits
function.
n
is 0, the function returns 0 and stops further recursion.n
will eventually be reduced to 0 through the recursive steps.n
and calculate the sum of their digits.