71.8k views
4 votes
C programming question

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

User Marthym
by
4.8k points

1 Answer

3 votes

Answer:

int digitSum(int n) {

int sum = 0;

while (n) {

sum += n % 10;

n /= 10;

}

return sum < 10 ? sum : digitSum(sum);

}

int main()

{

int n = 12345;

printf("Digit sum of %d is %d\\", n, digitSum(n));

}

Step-by-step explanation:

The recursion takes care of the repeated summing in case the sum has more than 1 digit.

User Squarism
by
4.6k points