C Program to Find Frequency of Characters in a String

Here we will write a C Program to find the frequency of characters in a string. For example in the word “Programming”, the frequency of “m” is 2, because m comes 2 times.

int main()
   char ch, str[200];
   int i, frequency=0;

   printf("Enter string: ");
   fgets(str, sizeof(str), stdin);
   printf("Enter a character to check its frequency: ");

       if(ch==str[i]) frequency++;

   printf("The frequency of %c is= %d",ch,frequency);
   return 0;


Enter string: Anyone can write code that a computer can understand, Good programmers write code that humans can understand.
Enter a character to check its frequency: a
The frequency of a is= 10

Enter string: Talk is cheap, show me the code.
Enter a character to check its frequency: z
The frequency of z is= 0

C program to find frequency of characters in a string, In this program we take input from user using fgets() method. The fgets() method read the string and also add newline character (conversion of the enter key) into the string. Later we take character to search the frequency and store it in the variable ch. Using if statement every character of string is checked. To count the frequency of character another variable frequency is used. Whenever the character of string is equal to the searching character, then the frequency is incremented. At the end of the string we get the final result and the result is displayed to the screen.

In this program for different methods of inputs of string, you may get different behaviours of the program so be careful.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

More C programming Examples on String

Leave a Comment

Your email address will not be published. Required fields are marked *