Sum of Digits Recursively
Given a non-negative integer, compute the sum of its digits using recursion. The digit sum is obtained by adding each individual digit together.
For example, the digit sum of 123 is 1 + 2 + 3 = 6. For 999 it is 9 + 9 + 9 = 27. For 0 it is 0. A single-digit number returns itself.
This problem introduces recursive thinking. The base case is when n is less than 10 (a single digit), in which case the sum is n itself. The recursive step extracts the last digit using modulo 10 and adds it to the sum of the remaining digits obtained by dividing n by 10.
Recursion is a fundamental problem-solving technique where a function calls itself on a smaller version of the same problem. Each call reduces the problem size until reaching the base case, at which point results propagate back up the call chain.
Edge cases include n = 0 (return 0), a single digit like 7 (return 7), and large numbers where recursion depth equals the number of digits.
Example Input & Output
4 + 8 + 2 = 14.
9 + 0 + 0 + 1 = 10.
A one-digit number is already its own digit sum.
Algorithm Flow

Solution Approach
Use recursion: sum the last digit with the sum of the remaining digits.
Base case: if n is a single digit (n < 10), return n. Recursive case: extract the last digit with n % 10, compute the sum of the remaining digits by calling digitSum(n / 10), and add them together.
Time complexity is O(d) where d is the number of digits. Space complexity is O(d) due to the recursion stack.
Best Answers
function sum_digits(n: integer) -> integer
dictionary
last, rest: integer
algorithm
if n < 10 then
return n
else
last <- n MOD 10
rest <- (n - last) / 10
return last + sum_digits(rest)
endif
endfunction
program sum_of_digits_recursive
dictionary
n: integer
algorithm
input(n)
output(sum_digits(n))
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
