basics · beginner · ~10 min

Sum of decimal digits

Loop with `n % 10` and `n /= 10`.

Challenge

Implement int digit_sum(int n) returning the sum of decimal digits of |n| (so negatives become positive first).

Why this matters

Digit-sum is the kernel of Luhn checksums, ISBN validation, and many small checksums in protocols.

Input format

Signed int.

Output format

Sum of digits as int.

Constraints

No string conversion.

Starter code

int digit_sum(int n) { /* TODO */ return 0; }

Common mistakes

Forgetting abs(n) — negative % gives negative digits in C.

Edge cases to handle

n == 0 → 0. n == INT_MIN — abs is undefined; cast to unsigned first.

Complexity

O(log10 n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.