C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Find frequency of characters

C Program: Find Frequency of Characters in a String

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[200];

    int freq[256] = {0};  // Frequency array for all ASCII characters

    int i;

 

    // Input string

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Count frequency of each character

    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] != '\n')  // Ignore newline character

            freq[(unsigned char)str[i]]++;

    }

 

    // Display frequency

    printf("\nCharacter frequencies:\n");

    for (i = 0; i < 256; i++) {

        if (freq[i] != 0)

            printf("'%c' = %d\n", i, freq[i]);

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter a string: IT Developer

Character frequencies:
'I' = 1
'T' = 1
' ' = 1
'D' = 1
'e' = 3
'v' = 1
'l' = 1
'o' = 1
'p' = 1
'r' = 1

Explanation

  • The program uses an integer array freq[256] to store the frequency of each ASCII character (0–255).
  • As each character is read, its ASCII value is used as an index to increment the frequency count.
  • Finally, all characters with non-zero frequencies are printed.