QUESTION 38 · Loop Applications
Write a C program to find the sum of digits of a non-negative integer.
5 marksAnswer in brief
The sum of digits is obtained by extracting each decimal digit and adding it to a running total.
Algorithm
- Read a non-negative integer n.
- Set sum to 0 and copy n to remaining.
- While remaining > 0, add remaining % 10 to sum and divide remaining by 10.
- Print sum.
Worked trace
For n = 472, the first digit is 2, sum becomes 2 and remaining becomes 47. Next, digit 7 makes sum equal to 9 and remaining becomes 4. Finally, digit 4 makes sum equal to 13 and remaining becomes 0. The condition is false, so the answer is 13.
Why keep a copy?
Dividing remaining changes it on each iteration. Keeping the original n allows it to be used later if required. The computation itself needs only the current remaining value and the sum.
Boundary cases
For input zero, the while body is skipped and sum stays zero, which is the correct sum of the digits of 0. The example rejects negative input to avoid extra sign-handling rules. It accepts values through 1000000000; the input token must fit long long.
Time and space complexity
If the number has d decimal digits, one digit is removed per iteration. The loop therefore performs d iterations for a positive number: O(d) time. Since the number of digits grows logarithmically with n, this can also be written O(log n) for n > 0. Only a fixed number of integer variables is stored, so auxiliary space is O(1).
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
long long n, remaining;
int sum = 0;
if (scanf("%lld", &n) != 1 || n < 0 || n > 1000000000LL) {
puts("Unsupported input"); return 1;
}
remaining = n;
while (remaining > 0) {
sum += (int)(remaining % 10);
remaining /= 10;
}
printf("Digit sum = %d\n", sum);
return 0;
}
Sample input and output
Input
472
Output
Digit sum = 13