#include <stdio.h>
int digit_sum(unsigned int n) {
int sum = 0;
while (n > 0) {
sum = sum + (n % 10);
n = n / 10;
}
return sum;
}
This function calculates the sum of the decimal digits of a non-negative integer. It repeatedly extracts the last digit using modulo 10, adds it to a running total, then removes that digit by dividing by 10, until the number becomes zero.
- The function works correctly for positive numbers, but consider what happens when the input is 0. The while loop condition `n > 0` will be false immediately, so the function returns 0. Is that the correct sum of digits for 0?
- The return type is `int`, but the parameter is `unsigned int`. Think about whether the sum of digits could ever exceed the range of `int` for very large inputs, and whether that matters for this function.