Numbers · beginner
C Program to Find the Sum of Digits of a Number
Find the sum of the digits of a number in C with a while loop using % 10 and / 10, handle negative numbers, and read the number with scanf().
- while loop
- modulus %
- integer division /
- abs()
Integer division is the key to working with digits in C: n % 10 is the last digit and n / 10 drops it, because dividing two ints discards the fraction. Repeating both until n is 0 visits every digit from right to left.
The program
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
if (scanf("%d", &n) != 1)
return 1;
int rest = abs(n);
int sum = 0;
while (rest > 0) {
sum += rest % 10;
rest /= 10;
}
printf("Sum of digits of %d is %d\n", n, sum);
return 0;
}-4721Sum of digits of -4721 is 14How it works
- scanf reads the number; the program stops if the input is not a number.
- abs() from stdlib.h removes the sign, so -4721 is treated like 4721.
- rest % 10 is the last digit, added to sum; rest /= 10 removes it.
- The loop ends when rest reaches 0, after one pass per digit: 1 + 2 + 7 + 4 = 14.
Another way: Recursive version
The sum of digits of n is its last digit plus the sum of digits of n / 10. The recursion stops at 0.
#include <stdio.h>
int digit_sum(int n) {
return n == 0 ? 0 : n % 10 + digit_sum(n / 10);
}
int main(void) {
printf("%d %d\n", digit_sum(4721), digit_sum(9999));
return 0;
}14 36Common mistakes
- Using a negative number without abs(): -4721 % 10 is -1 in C, so the loop condition rest > 0 fails immediately.
- Printing rest at the end instead of n: by then rest is 0.
- Using a double for the number: % does not work on floating-point values.
Try it yourself
- Also count the digits and print their average.
- Repeat the sum until one digit is left (digital root).
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.