data-structures · beginner · ~15 min
Sum a number's digits recursively.
Implement:
int sum_of_digits(int n);
Return the sum of the decimal digits of n (n >= 0), computed recursively.
n >= 0.
Digit sum.
Peel one digit per call.
#include <stddef.h>
/* Sum of the decimal digits of n (n>=0), computed recursively. */
int sum_of_digits(int n){ (void)n; return 0; }
Forgetting the base case for n < 10; using the wrong digit (n/10 vs n%10).
Single-digit n returns n.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.