Add up the digits of a number, recursively.
What to build
A short recursive function.
Requirements
- Write
int digit_sum(int n)using recursion, with no loop. - Print the result.
Input
One whole number.
Output
One number.
Constraints
The number is from 0 to 1000000000.
Example
Input:
123
Output:
6
Why it works
The sum of the digits is the last digit plus the sum of the digits of what is left, which is a smaller version of the same problem.
Examples
Example 1 · Input
123
Expected output
6
Example 2 · Input
9
Expected output
9
Hints
Hint 1
The base case is a number below 10.
Hint 2
n % 10 is the last digit, and n / 10 is the rest.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int digit_sum(int n) {
if (n < 10) {
return n;
}
return n % 10 + digit_sum(n / 10);
}
int main(void) {
int n;
scanf("%d", &n);
printf("%d\n", digit_sum(n));
return 0;
}