data-structures · beginner · ~15 min

Sum of digits

Sum a number's digits recursively.

Challenge

Implement:

int sum_of_digits(int n);

Return the sum of the decimal digits of n (n >= 0), computed recursively.

Input format

n >= 0.

Output format

Digit sum.

Constraints

Peel one digit per call.

Starter code

#include <stddef.h>
/* Sum of the decimal digits of n (n>=0), computed recursively. */
int sum_of_digits(int n){ (void)n; return 0; }

Common mistakes

Forgetting the base case for n < 10; using the wrong digit (n/10 vs n%10).

Edge cases to handle

Single-digit n returns n.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.