Code Logo

Sum of Digits Recursively

Published at19 Apr 2026
Recursion Easy 7 views
Like0

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.

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

Use recursion: sum the last digit with the sum of the remaining digits.

function digitSum(n)
  if n < 10 then return n
  return (n % 10) + digitSum(n / 10)

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

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