- Why
n /= 10peels off one digit at a time, and why this always terminates - How to handle the tricky case of zero, which would otherwise report 0 digits
- Why negative numbers need absolute-value treatment before the loop
- Why this loop is O(log n), not O(n) — and why that matters for large inputs
- How the same digit-by-digit traversal powers the other assignments in this series
Why Divide by 10?
Here's the whole idea in one sentence: dividing a positive integer by 10 with integer division removes its last digit. 1234 / 10 = 123, 123 / 10 = 12, 12 / 10 = 1, 1 / 10 = 0. Every division makes the number shorter by one digit, and once the number reaches 0, there are no more digits left to count.
This is the decimal-number equivalent of asking "how many times can you cut this thing in half before it's gone?" Except we're not cutting in half — we're removing exactly one digit each time. The number of cuts equals the number of digits. For 1234, four cuts. For 999999, six cuts. For 12, two cuts. The loop counts the cuts, and the count is the digit count.
That simple observation — "divide by 10, count one, repeat" — is the foundation of almost every digit-based program in this series. Counting digits is the simplest one. Reversing a number, summing digits, finding the largest digit, checking Armstrong numbers, and printing digits in reverse all reuse the same loop skeleton, with different things happening inside the body. If you understand this one cleanly, the rest are variations.
💡 In one line: dividing an integer by 10 removes its last digit, so counting the number of divisions until the number becomes 0 gives the digit count.
The Algorithm in Three Lines
In pseudocode, the whole thing is almost trivial:
count = 0
while n != 0:
n = n / 10
count = count + 1
print count
Three lines, and the whole program is essentially that plus input reading and output printing. The interesting part is the edge cases, which is where most beginner solutions get it wrong.
| Input | Expected digit count | Why this is worth checking |
|---|---|---|
| 0 | 1 | Loop would report 0 — the classic off-by-one bug |
| 7 | 1 | Single-digit positive — the loop runs exactly once |
| −7 | 1 | Negative single-digit — needs absolute value |
| 1234 | 4 | Ordinary positive — the standard case |
| −1234 | 4 | Negative — same magnitude, same digit count |
| 1000000 | 7 | Trailing zeros — the loop handles them naturally |
| 2147483647 | 10 | Largest int — the loop does 10 iterations |
The three cases that catch people are zero, negatives, and the boundary of int. Zero is the only case where a "natural" while loop returns the wrong answer (0 instead of 1). Negatives break the loop entirely if handled naively. And the largest int reminds you that the loop is bounded at 10 iterations — which is why this approach is fast regardless of input size.
Complete C Program
Program: count digits using a while loop
#include <stdio.h>
int main(void) {
int n;
printf("Enter an integer: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
return 1;
}
/* Zero is a one-digit number, but the loop would count it as 0 */
if (n == 0) {
printf("Number of digits = 1\n");
return 0;
}
/* Digit count depends on magnitude, not sign */
if (n < 0) n = -n;
int count = 0;
while (n != 0) {
n = n / 10;
count++;
}
printf("Number of digits = %d\n", count);
return 0;
}
And here's a variant that uses do-while instead, which handles zero automatically because the body runs before the condition is tested:
Variant using do-while — no zero case needed
#include <stdio.h>
int main(void) {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
if (n < 0) n = -n;
int count = 0;
do {
count++;
n = n / 10;
} while (n != 0);
printf("Number of digits = %d\n", count);
return 0;
}
Notice that the second version doesn't need the explicit zero check. That's because do-while always executes the body at least once — so for n = 0, it counts one iteration and then exits. This is the kind of cleanup that comes from understanding which loop fits the problem. The assignment asks for while, so the main program uses that, but it's worth knowing the do-while version is shorter and arguably more elegant.
Program Output
Enter an integer: 1234
Number of digits = 4
Try a few more. Input 0 and you should get 1. Input -98765 and you should also get 5 (the minus sign isn't a digit). Input 2147483647 (the largest int) and you should get 10. Input 7 and you should get 1. And input 1000000 — seven zeros and a one — and you should get 7.
Step-by-Step Explanation
Let's walk through 1234 and then look at the edge cases.
1. Reading input
scanf("%d", &n) reads a signed decimal integer. The check for != 1 catches the case where the user typed something that wasn't a number — no point continuing with a garbage value.
2. The zero special case
Zero is a one-digit number in decimal. But if we went straight to the loop without a check, the loop condition n != 0 would be false on entry, and count would stay at 0 — the wrong answer. There are two clean ways to fix this: an explicit early return (used in the main program), or switching to do-while (used in the variant above). Both are fine. The early return is arguably clearer because it makes the special case visible in the code rather than hidden in the loop choice.
3. Absolute value
For negatives, the sign bit is not a digit. −1234 has four digits, not five. Converting to positive with n = -n loses the sign, which is exactly what we want here. Note the small edge case: -INT_MIN overflows because INT_MIN's absolute value can't be represented as a positive int. That's a technicality most beginner programs ignore, and it's fine to ignore here — but worth knowing it exists.
4. The main loop
For 1234, the loop runs like this:
n = 1234,count = 0— conditionn != 0is truen = 1234 / 10 = 123,count = 1n = 123 / 10 = 12,count = 2n = 12 / 10 = 1,count = 3n = 1 / 10 = 0,count = 4- Condition
n != 0is now false — loop exits
Final count = 4. That's the digit count.
5. Why the loop always terminates
Because n = n / 10 with integer division always produces a value strictly less than n for positive n. The sequence of n values is 1234, 123, 12, 1, 0 — strictly decreasing, always non-negative. A strictly decreasing sequence of non-negative integers must reach 0 in finitely many steps. This is the same termination argument as Euclid's algorithm, and it's worth internalising because it applies to a whole class of "shrink the input" loops.
6. Why the loop is O(log n), not O(n)
If the input is n, the loop runs approximately log₁₀(n) + 1 times — the number of decimal digits of n. For 1234, that's 4. For 1,000,000, that's 7. For 2,147,483,647 (the largest int), that's 10. So even for the biggest possible input, the loop runs 10 iterations. Compare this with a loop like for (i = 0; i < n; i++) which would run 2 billion iterations for the same input — a huge difference. This is the practical payoff of picking the right algorithm.
7. A subtle trap: while (n) vs while (n != 0)
Both work in C, because 0 is falsy and any other integer is truthy. So while (n) is equivalent to while (n != 0). Some programmers prefer the shorter form; others prefer the explicit comparison because it makes the intent clearer. For a teaching program, the explicit version is better because a beginner reading it can see immediately what the loop is waiting for. Style preference, not correctness.
🎯 Remember this: dividing by 10 with integer division removes the last digit. Count the divisions until the number is 0, and you have the digit count. Handle zero specially (or use do-while), take absolute values for negatives, and remember the loop runs in O(log n) — at most 10 iterations for any 32-bit int.
Frequently Asked Questions
1. Why does the loop divide by 10 and not by some other number?
Because we're working in base 10 — decimal. If you're counting digits in binary, divide by 2. In octal, divide by 8. In hexadecimal, divide by 16. The pattern generalises: to count digits in base b, divide by b. Division by 10 removes one decimal digit per step, so the number of steps is the number of decimal digits.
2. Why doesn't the loop count zero as a digit?
If n = 0, the loop condition n != 0 is false on entry — the body never runs, and count stays 0. But zero is a one-digit number! This is the classic off-by-one bug in digit-count programs. Fix it either with an explicit early return for the zero case (as in the main program) or by switching to do-while, which always executes at least once.
3. Why take the absolute value of negative numbers?
Because the minus sign isn't a digit. −1234 has four digits, not five. The digit count depends only on the magnitude, not the sign. Without the absolute value, n / 10 on a negative input behaves differently: −1234 / 10 in C is −123 (truncation toward zero), then −12, then −1, then 0 — the count would still come out 4 because of the way integer division truncates. But it's fragile (the behaviour depends on truncation semantics), and taking absolute value first is clearer and avoids surprises.
4. Can I count digits without a loop?
Yes, one line: snprintf(NULL, 0, "%d", n) — this prints n into a zero-length buffer, returning the number of characters it would have written. For an integer, that's exactly the digit count. It handles negatives (adds 1 for the '-' sign), zero (returns 1), and everything else. Some people consider it clever; others consider it slow and fragile. For a loop assignment, use the loop. For production code, the snprintf trick works if the return value is checked carefully for negatives.
5. How is this used in the other assignments in this series?
Every digit-based program in this series uses the same loop skeleton. Sum of digits: sum += n % 10 then n /= 10. Reverse a number: rev = rev * 10 + n % 10 then n /= 10. Largest digit: if (n % 10 > max) max = n % 10 then n /= 10. Armstrong check: sum the cube (or digit-count-power) of each digit, which uses the digit count from this program. Once you understand this loop, the others are copy-paste-and-adjust.
6. What about very large numbers that don't fit in int?
If you need more range, use long long and scanf("%lld", &n). The logic is identical — divide by 10, count — but the loop can go up to about 20 iterations instead of 10. For even larger numbers (like 1000-digit factorials), you'd need strings, because no built-in integer type is big enough. But that's well beyond the scope of a loop assignment.
💡 Tip: After this program, try the do-while variant. Then try modifying it to count digits in base 2 (divide by 2), base 8 (divide by 8), or base 16 (divide by 16). You'll see that the loop skeleton stays the same — only the divisor changes. That's the essence of a well-designed algorithm: the structure is independent of the details.