Sum of Digits Recursively
Have you ever looked at a long number and tried to add up all its individual digits in your head? For the number 1234, the sum would be 1 + 2 + 3 + 4, which equals 10. This is a common logic task used in data validation and checksums.
While you could solve this with a loop, there is a very natural recursive way to think about it. You can peel off the last digit of the number using the MOD operator, and then ask the computer to calculate the sum of the remaining digits. You just keep peeling off digits until there is nothing left to add.
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
To solve this recursively, we need to identify how to "shrink" our number in each step. We can get the last digit by using n MOD 10 and get the rest of the number by using n DIV 10.
Our base case is reached when the number becomes 0, meaning we have processed all the digits. Until then, we add the current last digit to the result of a recursive call on the remaining portion of the number.
For example, if you input 567, the function first takes 7 and calls itself for 56. Then it takes 6 and calls itself for 5, and finally takes 5 and calls itself for 0. The addition happens as the calls return, giving you 5 + 6 + 7 = 18.
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.
