basics · beginner · ~10 min
Loop with `n % 10` and `n /= 10`.
Implement int digit_sum(int n) returning the sum of decimal digits of |n| (so negatives become positive first).
Digit-sum is the kernel of Luhn checksums, ISBN validation, and many small checksums in protocols.
Signed int.
Sum of digits as int.
No string conversion.
int digit_sum(int n) { /* TODO */ return 0; }
Forgetting abs(n) — negative % gives negative digits in C.
n == 0 → 0. n == INT_MIN — abs is undefined; cast to unsigned first.
O(log10 n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.