Write a C program to count frequency of each character in a string using loop. How to find frequency of each characters in a string in C programming. Logic to count frequency of each character in a given string in C program.
Example
Input
Input string: Codeforwin
Output
Frequency of all characters in the given string: 'c' = 1 'd' = 1 'e' = 1 'f' = 1 'i' = 1 'n' = 1 'o' = 2 'r' = 1 'w' = 1
Required knowledge
Basic C programming, If else, For loop, Array, String
Read more – Program to count frequency of each element in given array
Logic to count frequency of each character
There are many algorithms to count frequency of each character. Here I am explaining the easiest one.
- Input string from user, store it in some variable say str.
- To count and store frequency of each alphabet we need an array, say freq[26]. An array of size 26 (since there are 26 alphabets). Each element of the array will hold the occurrence of specific alphabet. For example
array[0] will hold the occurrence of a or A alphabet, similarly
array[1] will hold frequency of b and so on
array[25] will hold frequency of z. - Before you begin any processing with the string make sure that freq array elements are initialized to 0.
- Then for each character ch in the string str repeat next step.
- If ch == ‘a’ then increment the value of freq[0]++ by one. Similarly if(ch == ‘z’) then increment freq[25]++.
Now, to make things little easier and to work with every character in the given string we use below logic to increment freq. We use,
freq[ch – 97] (For lowercase alphabets) and
freq[ch – 65] (For uppercase alphabets) - You might think why we have used these values ch – 97 and what it will do? Since, ASCII value of a is 97, b is 98 and so on. Suppose ch = ‘c’ then we need to increment the value of freq[2] by one.
Lets, do a simple mathematics
=> freq[ ch – 97 ]
=> freq[ 99 – 97 ] (since ASCII value of c=97)
=> freq[ 2 ]
which works.
You can apply the same mathematics with the upper case alphabets i.e. if(ch == ‘Z’) then we need to perform freq[ ch – 65 ].
Program to count frequency of each character
Output
Enter any string: Codeforwin Frequency of all characters in the given string: 'c' = 1 'd' = 1 'e' = 1 'f' = 1 'i' = 1 'n' = 1 'o' = 2 'r' = 1 'w' = 1
Happy coding