C program to find frequency of each digit in a string

In C, finding the frequency of each digit in a string involves scanning through the string character by character and counting occurrences of digits (0-9). We use an array to store the frequency count for each digit.

Syntax

int freq[10] = {0};  // Array to store frequency of digits 0-9
if (str[i] >= '0' && str[i] <= '9') {
    freq[str[i] - '0']++;  // Increment count for the digit
}

Algorithm

To solve this problem, we follow these steps −

  • Create an array freq of size 10 and initialize all elements to 0
  • Iterate through each character in the string
  • If the character is a digit (between '0' and '9'), increment the corresponding frequency counter
  • Display all digits that have a frequency greater than 0

Example

Let us see the implementation to find frequency of each digit in a string −

#include <stdio.h>
#include <string.h>

void findDigitFrequency(char *s) {
    int freq[10] = {0};
    
    // Count frequency of each digit
    for (int i = 0; i < strlen(s); i++) {
        if (s[i] >= '0' && s[i] <= '9') {
            freq[s[i] - '0']++;
        }
    }
    
    // Display frequencies
    for (int i = 0; i < 10; i++) {
        if (freq[i] > 0) {
            printf("(Number %d, Freq %d)<br>", i, freq[i]);
        }
    }
}

int main() {
    char s[] = "we85abc586wow236h69";
    printf("String: %s<br>", s);
    printf("Digit frequencies:<br>");
    findDigitFrequency(s);
    return 0;
}
String: we85abc586wow236h69
Digit frequencies:
(Number 2, Freq 1)
(Number 3, Freq 1)
(Number 5, Freq 2)
(Number 6, Freq 3)
(Number 8, Freq 2)
(Number 9, Freq 1)

How It Works

The program uses ASCII value arithmetic to convert characters to array indices. When we encounter a digit character like '5', we subtract '0' from it to get the numeric value 5, which becomes the index in our frequency array.

Key Points

  • The expression s[i] - '0' converts a digit character to its numeric value
  • We check s[i] >= '0' && s[i] to ensure the character is a digit
  • Time complexity is O(n) where n is the length of the string
  • Space complexity is O(1) as we use a fixed-size array of 10 elements

Conclusion

This approach efficiently counts digit frequencies using an array-based counting technique. It handles mixed strings containing both letters and digits, providing a clean solution for digit frequency analysis.

Updated on: 2026-03-15T14:24:51+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements