DSA Factory
Free lessonsRecursion · Stage 0 · A function that calls itself · Step 1

Sum of digits

Answer a tiny case directly, and hand everything else to a smaller call. About 8 minutes.

A function may call itself

The digits of 4729 add up to 9 plus the digits of 472, and 472 is the same kind of question, just smaller. Like Russian nesting dolls, each doll contains a smaller copy of itself. So the answer for the whole number is the last digit plus the answer for the rest.

A function that calls itself like this is recursive. Trust the smaller call to return the right answer, and add your part.

The remainder after dividing by 10: is the last digit, and dividing drops it.
The smaller call: handles every digit except the last.
sum_digits(4729), one call at a time
4
0
7
1
2
2
9
3
last

sum_digits(4729): keep the last digit 9, and ask sum_digits(472).

Move 1 of 5

Every recursion needs a base case

If the function always called itself, it would never stop, like a dream inside a dream inside a dream. So pick a case small enough to answer directly: a number with one digit is its own digit sum.

Check it first, before the smaller call. Each call must also move closer to the base case, or the calls never end.

Base case first: check it before you call again.
No base case? the program runs out of room for calls and crashes.
In code
def sum_digits(n):
    if n < 10:
        return n
    return n % 10 + sum_digits(n // 10)
Quick check

sum_digits(305) returns 5 + sum_digits(30). What does sum_digits(30) do?

  1. AReturns 0 + sum_digits(3)
  2. BReturns 3 + sum_digits(0)
  3. CStops, because 30 ends in 0
Show the answer

Returns 0 + sum_digits(3). 30 isn't below 10, so it keeps its last digit 0 and calls sum_digits(3), a base case. The total is 5 + 0 + 3 = 8.

Your problem

Sum of digits

Return the sum of the digits of n. Use recursion: answer a one-digit n directly, and let a smaller call handle the rest.

Example
n = 4729 → 22

0 ≤ n ≤ 2,000,000,000 · at most 10 digits, so at most 10 calls deep

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding