Code Logo

Sum of Digits Recursively

Published at19 Apr 2026
Recursion Easy 3 views
Like0

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.

Learn about our pseudocode specification
Guide

Example Input & Output

Example 1
Input
n = 482
Output
14
Explanation

4 + 8 + 2 = 14.

Example 2
Input
n = 9001
Output
10
Explanation

9 + 0 + 0 + 1 = 10.

Example 3
Input
n = 7
Output
7
Explanation

A one-digit number is already its own digit sum.

Algorithm Flow

Recommendation Algorithm Flow for Sum of Digits Recursively
Recommendation Algorithm Flow for Sum of Digits Recursively

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.

function sum_digits(n)
   if n = 0 then
      return 0
   else
      return (n MOD 10) + sum_digits(n DIV 10)
   endif
endfunction

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

Pseudocode - Approach 1
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))
endprogram