How to find the frequency of each digit (0–9) in a number with C

1 Answer

0 votes
#include <stdio.h>

/*
    Function: countDigitFrequency
    Purpose:  Counts how many times each digit (0–9) appears in a number.
    Parameters:
        - n: the number whose digits we want to count
        - freq: an array of size 10 that stores the frequency of each digit
                freq[0] = count of digit '0'
                freq[1] = count of digit '1'
                ...
                freq[9] = count of digit '9'
    Explanation:
        We repeatedly extract the last digit using n % 10,
        then remove that digit using n / 10.
*/
void countDigitFrequency(int n, int freq[]) {
    // Process each digit of the number
    while (n > 0) {
        int digit = n % 10;   // extract last digit
        freq[digit]++;        // increase its frequency
        n /= 10;              // remove last digit
    }
}

int main() {

    int n = 79712622;   // the number we want to analyze

    int freq[10] = { 0 };    // array to store digit frequencies

    // Call the function to count digit frequencies
    countDigitFrequency(n, freq);

    // Display the result
    printf("Digit frequencies in %d:\n\n", n);

    for (int i = 0; i < 10; i++) {
        if (freq[i] != 0)
            printf("Digit %d occurs %d times\n", i, freq[i]);
    }

    return 0;
}

/*
run:

Digit frequencies in 79712622:

Digit 1 occurs 1 times
Digit 2 occurs 3 times
Digit 6 occurs 1 times
Digit 7 occurs 2 times
Digit 9 occurs 1 times

*/

 



answered Jul 4, 2020 by avibootz
edited Jul 2 by avibootz
...