Loop Assignment 9 — Count a Specific Digit Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Count the Occurrences of a Specific Digit in an Integer Using a For Loop

📑 On this page:
  • Counting Matches, Not Just Extracting Digits
  • Fitting the Loop Into a For Header
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • 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.

Diagram showing the number 4529855 with each '5' highlighted, illustrating three occurrences of the digit 5

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
452985553Ordinary case — 5 appears at positions 3, 6, 7
452985581Single occurrence
452985570Digit doesn't appear — should be 0, not error
001Zero has exactly one digit, and it's 0
050Zero doesn't contain 5
−555554Minus sign isn't counted
1000004Four 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:

  1. Empty initializer — n is already set from scanf. Writing for (; ...) is valid C, though some style guides find it awkward. An alternative is to introduce a temporary int m = n; and write for (int m = n; m > 0; m /= 10), which makes the loop header fully self-contained.
  2. Condition n > 0 — loop continues as long as there are digits left to process.
  3. Update n /= 10 — removes the last digit after each iteration. Because this is in the loop header, the body doesn't need to update n itself.

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:

  1. n = 4529855, digit = 5, matches → count = 1, n = 452985
  2. n = 452985, digit = 5, matches → count = 2, n = 45298
  3. n = 45298, digit = 8, no match → count = 2, n = 4529
  4. n = 4529, digit = 9, no match → count = 2, n = 452
  5. n = 452, digit = 2, no match → count = 2, n = 45
  6. n = 45, digit = 5, matches → count = 3, n = 4
  7. n = 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.

📖 Related Tutorials

  • 6. Count the Digits in an Integer Using a While Loop
  • 7. Find the Largest Digit in an Integer Using a Do-While Loop
  • 8. Find the Smallest Digit in an Integer Using a While Loop
  • 10. Calculate the Product of All Digits Using a While Loop
  • 12. Output Digits in Reverse Order Using a While Loop
  • C FOR Loop
  • While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 8. Find the Smallest Digit in an Integer Using a While Loop   ||   Next Topic: -->> 10. Calculate the Product of All Digits Using a While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.