Recursive Digit Sum
Completed
Write a recursive int digit_sum(int n) and print the digit sum of each input number.
Input
n, then n non-negative integers.
Output
n lines.
Example
Input
3 12345 0 999
Output
15 0 27
Editor
C
Hints
last digit + digit_sum(rest)
Solution explanation
Each call handles one digit and delegates the rest.
Show solution
#include <stdio.h>
int digit_sum(int n) {
if (n < 10) return n;
return n % 10 + digit_sum(n / 10);
}
int main() {
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
printf("%d\n", digit_sum(x));
}
return 0;
}