C Program to Find Sum of Digits Using While Loop
digit = num % 10, adding it to a sum, and then removing the last digit with num = num / 10 until num becomes zero.Examples
How to Think About It
%, add it to a total sum, then remove that digit by dividing the number by 10. Repeat this until no digits remain.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 123 through the code
Initial values
num = 123, sum = 0
First iteration
digit = 123 % 10 = 3; sum = 0 + 3 = 3; num = 123 / 10 = 12
Second iteration
digit = 12 % 10 = 2; sum = 3 + 2 = 5; num = 12 / 10 = 1
Third iteration
digit = 1 % 10 = 1; sum = 5 + 1 = 6; num = 1 / 10 = 0
Loop ends
num is now 0, exit loop and print sum = 6
| num before iteration | digit extracted | sum after addition | num after division |
|---|---|---|---|
| 123 | 3 | 3 | 12 |
| 12 | 2 | 5 | 1 |
| 1 | 1 | 6 | 0 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number because it gives the remainder after division by 10.
Step 2: Add digit to sum
Add the extracted digit to the running total stored in sum.
Step 3: Remove last digit
Divide the number by 10 using integer division num /= 10 to discard the last digit and move to the next.
Step 4: Repeat until done
Continue the loop until num becomes zero, meaning all digits have been processed.
Alternative Approaches
#include <stdio.h> #include <string.h> int main() { char num[20]; int sum = 0; printf("Enter a number: "); scanf("%s", num); for (int i = 0; i < strlen(num); i++) { sum += num[i] - '0'; } printf("Sum of digits = %d\n", sum); return 0; }
#include <stdio.h> int sumDigits(int num) { if (num == 0) return 0; return (num % 10) + sumDigits(num / 10); } int main() { int num; printf("Enter a number: "); scanf("%d", &num); printf("Sum of digits = %d\n", sumDigits(num)); return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time complexity is proportional to the number of digits, O(d).
Space Complexity
Only a few integer variables are used, so space complexity is constant, O(1).
Which Approach is Fastest?
The while loop method is fastest and uses least memory compared to string or recursive methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop with integer | O(d) | O(1) | Simple and efficient for normal integers |
| For loop with string input | O(d) | O(d) | Very large numbers or when input is string |
| Recursion | O(d) | O(d) | Learning recursion, less efficient for large inputs |