C Program to Count Digits in a Number
while (num != 0) { num /= 10; count++; }.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <stdlib.h> int main() { int num, count = 0; printf("Enter an integer: "); scanf("%d", &num); if (num == 0) { count = 1; } else { num = abs(num); while (num > 0) { num /= 10; count++; } } printf("Number of digits: %d\n", count); return 0; }
Dry Run
Let's trace the input 12345 through the code to count digits.
Input number
num = 12345, count = 0
Check if zero
num is not zero, proceed
Convert to absolute
num = 12345 (already positive)
Divide and count loop
Loop 1: num=12345/10=1234, count=1 Loop 2: num=1234/10=123, count=2 Loop 3: num=123/10=12, count=3 Loop 4: num=12/10=1, count=4 Loop 5: num=1/10=0, count=5
Loop ends
num=0, count=5
| Iteration | num | count |
|---|---|---|
| 1 | 1234 | 1 |
| 2 | 123 | 2 |
| 3 | 12 | 3 |
| 4 | 1 | 4 |
| 5 | 0 | 5 |
Why This Works
Step 1: Handle zero input
If the number is zero, it has exactly one digit, so we set count to 1 immediately.
Step 2: Use absolute value
Negative numbers are converted to positive using abs() so digit counting works the same.
Step 3: Count digits by division
Dividing the number by 10 removes the last digit each time, so counting how many times this happens until zero gives the total digits.
Alternative Approaches
#include <stdio.h> #include <string.h> int main() { char str[20]; printf("Enter an integer: "); scanf("%s", str); int length = strlen(str); int count = (str[0] == '-') ? length - 1 : length; printf("Number of digits: %d\n", count); return 0; }
#include <stdio.h> #include <stdlib.h> int countDigits(int num) { num = abs(num); if (num < 10) return 1; return 1 + countDigits(num / 10); } int main() { int num; printf("Enter an integer: "); scanf("%d", &num); printf("Number of digits: %d\n", countDigits(num)); return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used, so space complexity is constant, O(1).
Which Approach is Fastest?
The division loop is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Division loop | O(d) | O(1) | Efficient and simple digit counting |
| String conversion | O(d) | O(d) | Easy to implement but uses extra memory |
| Recursive counting | O(d) | O(d) | Elegant but uses stack memory |