- How to write a digit-extraction loop using the compact
for (; n > 0; n /= 10)form - How to compare each extracted digit against a target and count matches
- Why the initial value of the counter should be 0 — and why the loop's end state matters
- How to handle the tricky zero case (which the loop would otherwise skip)
- How to extend the same program to count all ten digits in one pass
Counting Matches, Not Just Extracting Digits
The last few programs in this series extracted every digit and did something with the whole set — counting them, finding the maximum, finding the minimum. This program works a bit differently. It only cares about one specific digit — say, how many times does the digit 5 appear in the number 4529855? — and everything else is ignored.
That makes it simpler in one way (no need to track running state across iterations; just a counter) and trickier in another (zero becomes a special case that catches people out). The digit 5 appears three times in 4529855. The digit 8 appears once. The digit 7 appears zero times, and that's a valid answer — not an error.
The most common use is in data cleaning and validation. How many times does '0' appear in an account number? How many '9's are in this phone number? How many digits between 3 and 7 appear in a password? The counting logic is the same regardless of the application; only the target digit changes.
💡 In one line: extract each digit with n % 10, increment a counter every time it matches the target, and shrink n with n /= 10. When n reaches 0, the counter is the answer.
Fitting the Loop Into a For Header
The previous digit programs used while and do-while. This one uses for, and that changes how the loop is written. A for loop has three parts separated by semicolons: initialisation, condition, and update. The digit-extraction loop maps naturally to the second and third parts:
for (; n > 0; n /= 10) {
/* body */
}
The empty first slot is legitimate — n is already initialised from scanf. Some programmers write for (; n; n /= 10) (using n as a truthy value), others prefer for (; n > 0; n /= 10) for clarity. Both work. The explicit > 0 is arguably easier to read for a beginner.
The update step n /= 10 is now inside the loop header, which means the body only needs to do the comparison and the counting. That's tighter than the while version, where the shrink-step had to be written out at the end of the body. This is the whole point of for — when the loop has a clear initial condition, iteration invariant, and update, all three fit into the header where a reader can see them at a glance.
| Input | Target digit | Expected count | Why this case |
|---|---|---|---|
| 4529855 | 5 | 3 | Ordinary case — 5 appears at positions 3, 6, 7 |
| 4529855 | 8 | 1 | Single occurrence |
| 4529855 | 7 | 0 | Digit doesn't appear — should be 0, not error |
| 0 | 0 | 1 | Zero has exactly one digit, and it's 0 |
| 0 | 5 | 0 | Zero doesn't contain 5 |
| −5555 | 5 | 4 | Minus sign isn't counted |
| 10000 | 0 | 4 | Four zeros — count each one |
Notice the zero case carefully. For input 0 with target 0, the answer is 1 — the number zero has one digit, and that digit is 0. But a for (; n > 0; ...) loop never runs for n = 0, so it would report 0. That's the bug. The program below handles it explicitly.
Complete C Program
Program: count how many times a digit appears in an integer
#include <stdio.h>
int main(void) {
int n, d;
printf("Enter an integer: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
return 1;
}
printf("Enter the digit to count (0-9): ");
if (scanf("%d", &d) != 1 || d < 0 || d > 9) {
printf("Invalid digit. Please enter a value between 0 and 9.\n");
return 1;
}
/* Digit extraction only cares about magnitude */
if (n < 0) n = -n;
/* Handle the special case: 0 contains exactly one 0 */
int count = 0;
if (n == 0) {
if (d == 0) count = 1;
printf("Digit %d appears %d time(s)\n", d, count);
return 0;
}
/* The for loop's three parts: no initializer (n already set),
condition n > 0, and update n /= 10 */
for (; n > 0; n /= 10) {
int digit = n % 10;
if (digit == d) {
count++;
}
}
printf("Digit %d appears %d time(s)\n", d, count);
return 0;
}
And here is a more ambitious variant that counts every digit from 0 to 9 in a single pass. It's the natural extension of the same idea, and it's a common interview follow-up:
Extension: count all ten digits in one pass
#include <stdio.h>
int main(void) {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
if (n < 0) n = -n;
/* freq[d] will hold how many times digit d appears */
int freq[10] = {0};
/* Same loop, but increment freq[digit] instead of a single counter */
for (; n > 0; n /= 10) {
freq[n % 10]++;
}
for (int d = 0; d < 10; d++) {
if (freq[d] > 0) {
printf("Digit %d appears %d time(s)\n", d, freq[d]);
}
}
return 0;
}
The array-based version does exactly the same work per iteration as the single-counter version, but it keeps all ten counts instead of one. For the single-digit problem, the array is overkill. For "show me a histogram of digit frequencies", it's the right tool.
Program Output
Enter an integer: 4529855
Enter the digit to count (0-9): 5
Digit 5 appears 3 time(s)
A few more cases to try. For 4529855 with target 8, you should get 1. For 4529855 with target 7, you should get 0. For 0 with target 0, you should get 1. For −5555 with target 5, you should get 4 (the minus sign isn't counted). For 10000 with target 0, you should get 4 — you have to count each of the four zeros, not just note their presence.
Step-by-Step Explanation
Let's walk through 4529855 with target digit 5.
1. Input and validation
The program reads both the number and the target digit. The check for d >= 0 && d <= 9 is important — if the user enters something like 15 or −3, the loop's comparison would never match any single extracted digit, and the program would report 0 without explaining why. Better to reject the input up front with a clear message.
2. Normalising the number
As in the previous digit programs, negatives are converted to positives. For −4529855, this becomes 4529855. The minus sign isn't a digit, so it doesn't belong in the count.
3. The zero case
For n = 0, the loop body never runs, so count stays at 0. But 0 has one digit — namely 0. If the target is 0, the answer should be 1. If the target is anything else, the answer should be 0. The early return handles both, and avoids dragging this special case through the rest of the logic.
4. The for loop in detail
The loop is written as for (; n > 0; n /= 10). Here's what each part does:
- Empty initializer —
nis already set fromscanf. Writingfor (; ...)is valid C, though some style guides find it awkward. An alternative is to introduce a temporaryint m = n;and writefor (int m = n; m > 0; m /= 10), which makes the loop header fully self-contained. - Condition
n > 0— loop continues as long as there are digits left to process. - Update
n /= 10— removes the last digit after each iteration. Because this is in the loop header, the body doesn't need to updatenitself.
The body is just two lines: extract the last digit, and increment count if it matches.
5. The trace for 4529855, target 5
The loop runs seven times — once per digit:
n = 4529855, digit = 5, matches → count = 1, n = 452985n = 452985, digit = 5, matches → count = 2, n = 45298n = 45298, digit = 8, no match → count = 2, n = 4529n = 4529, digit = 9, no match → count = 2, n = 452n = 452, digit = 2, no match → count = 2, n = 45n = 45, digit = 5, matches → count = 3, n = 4n = 4, digit = 4, no match → count = 3, n = 0
Loop exits when n reaches 0. Final answer: 3.
6. Why the counter must start at 0
The counter accumulates matches. If you started at 1 (for example, thinking "every number has at least one match"), you'd overcount in every case. Starting at 0 and incrementing only on an actual match keeps the count honest — zero matches is a valid answer (the target digit simply doesn't appear). This is different from the "at least one digit" reasoning behind the do-while in earlier assignments — the loop always runs at least once for a valid input, but the counter can correctly end at 0 if no digit matches.
7. Extension: counting all digits
The array-based variant replaces count with freq[10]. The loop body becomes freq[n % 10]++ — one line instead of three. This is what makes the array approach so elegant: the "which digit" question is answered by the index, so there's no need for explicit comparison. It's also a natural stepping stone to the histogram problem, which appears in more advanced algorithm questions.
🎯 Remember this: extract each digit, compare to the target, count matches. The for loop's update step (n /= 10) does the shrinking, so the body only has to handle the comparison. Zero is a special case that needs explicit handling — otherwise the loop skips it and reports 0 when the correct answer might be 1.
Frequently Asked Questions
1. Why is the initializer empty in the for loop?
Because n is already set — it came straight from scanf. The for header wants three parts separated by semicolons, but any of them can be empty if the corresponding action is already done or not needed. Writing for (; n > 0; n /= 10) is valid C, and it makes the loop's essential parts visible at a glance. If the empty first slot bothers you, introduce a temporary variable: for (int m = n; m > 0; m /= 10) — this works too, and has the advantage of not destroying n in case you need it later.
2. What if the target digit is larger than 9 or negative?
That's an error. Digits are between 0 and 9, so if the user enters 15 or −3, the program should reject it. That's why the check is there: if (scanf(...) != 1 || d < 0 || d > 9). Without it, the loop would compare each extracted digit (0–9) to an out-of-range target (like 15) and always find 0 matches, which is technically "correct" but confusing — the user thinks the digit appears nowhere, when really they entered an invalid digit. Better to reject it up front.
3. How is this different from the count-digits program?
The count-digits program counts how many digits total, regardless of value — one increment per iteration. This program counts how many match a specific digit — one increment only when the extracted digit equals the target. So the count can be 0 (target digit doesn't appear), which would never happen in the count-digits program for a valid input. Same loop skeleton, different increment condition.
4. Can I count multiple digits at once?
Yes — the array-based extension shown on this page does exactly that. Instead of a single counter, use int freq[10] = {0};, and replace the body with freq[n % 10]++. After the loop, freq[d] tells you how many times digit d appears, for every d from 0 to 9. This is slightly more expensive than counting a single digit (10 counters instead of 1), but it gives you all ten answers in one pass — useful when you don't know in advance which digit the user cares about.
5. What if I want to count occurrences of a multi-digit number, like how many times "42" appears in 14242142?
That's a different problem — and it's not solvable with a digit-extraction loop, because it requires looking at two consecutive digits rather than one. You'd typically convert the number to a string and use substring search (a string-matching algorithm like KMP or a simple built-in function). The digit-counting approach in this program only works for single digits. For multi-digit patterns, change the representation from int to char[].
6. How does this relate to the "how many 1s in a binary representation" program?
Same idea, different base. To count 1s in a binary representation, extract bits with n % 2 and shrink with n /= 2. Everything else is identical — the comparison is if (n % 2 == 1) count++. The program in assignment 17 (count set bits) uses exactly this approach with a while loop; swapping in a for loop would work the same way. This is a great demonstration that the digit-extraction pattern generalises across number systems.
💡 Tip: Once this program clicks, try the array-based extension and print all ten counts. Compare it to a histogram plot. Then notice that the "which digits appear in this number" question is really a histogram question — every digit contributes to exactly one bucket. This is the same data structure that powers word frequency counts, letter frequency counts, and voting tallies. One loop, one pattern, many applications.