C Program to Find Sum of Digits of a Number
num % 10, adds it to a sum, and reduces the number by num / 10 until the number is zero.Examples
How to Think About It
num % 10, add it to a running total, then remove that digit by dividing the number by 10 using num / 10. Repeat until the number becomes zero.Algorithm
Code
#include <stdio.h> int main() { int num, sum = 0, digit; printf("Enter a number: "); scanf("%d", &num); if (num == 0) { printf("Sum of digits = 0\n"); return 0; } while (num > 0) { digit = num % 10; sum += digit; num /= 10; } printf("Sum of digits = %d\n", sum); return 0; }
Dry Run
Let's trace the input 1234 through the code
Initial input
num = 1234, sum = 0
First iteration
digit = 1234 % 10 = 4, sum = 0 + 4 = 4, num = 1234 / 10 = 123
Second iteration
digit = 123 % 10 = 3, sum = 4 + 3 = 7, num = 123 / 10 = 12
Third iteration
digit = 12 % 10 = 2, sum = 7 + 2 = 9, num = 12 / 10 = 1
Fourth iteration
digit = 1 % 10 = 1, sum = 9 + 1 = 10, num = 1 / 10 = 0
Loop ends
num is 0, exit loop, sum = 10
| Iteration | num | digit | sum |
|---|---|---|---|
| 1 | 1234 | 4 | 4 |
| 2 | 123 | 3 | 7 |
| 3 | 12 | 2 | 9 |
| 4 | 1 | 1 | 10 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number, which we add to the sum.
Step 2: Remove last digit
Dividing the number by 10 with num /= 10 removes the last digit, preparing for the next iteration.
Step 3: Repeat until done
We repeat this process until the number becomes zero, ensuring all digits are added.
Alternative Approaches
#include <stdio.h> int sumDigits(int n) { if (n == 0) return 0; return (n % 10) + sumDigits(n / 10); } int main() { int num; printf("Enter a number: "); scanf("%d", &num); printf("Sum of digits = %d\n", sumDigits(num)); return 0; }
#include <stdio.h> #include <string.h> int main() { char numStr[20]; int sum = 0; printf("Enter a number: "); scanf("%s", numStr); for (int i = 0; i < strlen(numStr); i++) { sum += numStr[i] - '0'; } printf("Sum of digits = %d\n", sum); return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time depends on the number of digits d.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The iterative method is fastest and uses least memory; recursion adds overhead, and string conversion uses extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(d) | O(1) | Simple and efficient |
| Recursion | O(d) | O(d) | Elegant but uses more memory |
| String conversion | O(d) | O(d) | Easy digit access but extra space |