Question 2591
Consider the following methods. What is printed?
public static int sumDigits(int n) {
if (n < 10) { return n; }
return n % 10 + sumDigits(n / 10);
}
public static int digitalRoot(int n) {
int s = sumDigits(n);
if (s < 10) { return s; }
return digitalRoot(s);
}
System.out.println(digitalRoot(9999));Main Solution
Step 1: Call digitalRoot(9999)
Inside digitalRoot, we first call sumDigits(9999).
Step 2: Trace sumDigits(9999)
sumDigits recursively sums the digits of its argument:
sumDigits(9999)= 9 +sumDigits(999)sumDigits(999)= 9 +sumDigits(99)sumDigits(99)= 9 +sumDigits(9)sumDigits(9)= 9 (base case: 9 < 10)
Unwinding: 9 + 9 + 9 + 9 = 36
Step 3: Back in digitalRoot(9999)
s = 36. Since 36 ≥ 10, we call digitalRoot(36).
Step 4: Call digitalRoot(36)
Calls sumDigits(36): 36 % 10 = 6, then sumDigits(3) = 3. So sumDigits(36) = 6 + 3 = 9.
s = 9. Since 9 < 10, return 9.
Step 5: Result
digitalRoot(9999) returns 9, so System.out.println prints 9.
The correct answer is B) 9.
Teacher Explanation
sumDigits computes the digit sum recursively. digitalRoot repeatedly applies sumDigits until the result is a single digit. For 9999, the digit sum is 36, and the digit sum of 36 is 9, which is a single digit — so the answer is 9. This is the classic "digital root" algorithm.
Education Coach Advice
When tracing recursive methods that call each other (mutual recursion), track each call carefully on paper. Write out the call stack step by step. Pay special attention to the base case condition — here, the loop continues as long as the result is ≥ 10, so always check whether the returned value satisfies the base case before stopping your trace.
Traps
Option A (36) is the most common trap: students correctly compute sumDigits(9999) = 36 but forget that digitalRoot continues recursing because 36 ≥ 10. They stop one step too early.
Option C (18) might be chosen by students who miscount the digits or make an arithmetic error in the first digit sum.
Option D (1) is unlikely but could result from confusing the algorithm with something else entirely.
Answer images

