C Program to Find Frequency of Characters in a String

We first take a string as input from user. Input string may contain any ASCII characters like lower and upper case alphabets, space characters etc. There are 256 ASCII characters and their corresponding integer values are from 0 to 255. We have to count the frequency of characters in input string.

For Example
Input String : Apple
A : 1 times
e : 1 times
l : 1 times
p : 2 times

C program to count frequency of characters of a string

In this program, we first take a string as input from user using gets function. We will use an integer array of length 256 to count the frequency of characters. We initialize frequency array element with zero, which means initially the count of all characters are zero. We scan input string from index 0 till null character and for every character we increment the array element corresponding to it’s ASCII value.

For Example
A’s ASCII value is 65
frequency[‘A’]++ is equal to frequency[65]++
Every index in frequency array corresponds to a character’s frequency whose ASCII value is equal to index.

Finally we scan frequency array form index 0 to 256 and prints the frequency of the characters whose corresponding value in frequency array is non-zero.

C Program to Find Frequency of Characters in a String

/*
* C Program to count frequency of characters in string
*/
#include <stdio.h>
#include <conio.h>
 
int main(){
    char inputString[100];
    /* Declare a frequency counter array of size 256 
     * (for all ASCII characters) and initialize it with zero 
     */
    int index, frequency[256] = {0};
    printf("Enter a String\n");
    gets(inputString);
    for(index=0; inputString[index] != '\0'; index++){
        /* Populate frequency array */
        frequency[inputString[index]]++;
    }
    /* Print characters and their frequency */
    printf("\nCharacter   Frequency\n");
    for(index=0; index < 256; index++){
        if(frequency[index] != 0){
            printf("%5c%10d\n", index, frequency[index]);                    
        }
    }
 
    getch();
    return 0;
}

Program Output

Enter a String
Tech-Crash-Course

Character   Frequency
    -         2
    C         2
    T         1
    a         1
    c         1
    e         2
    h         2
    o         1
    r         2
    s         2
    u         1