Home / Programs / C Program to Find the Frequency of Characters in a String
🚀 Programming Example

C Program to Find the Frequency of Characters in a String

👁 939 Views
💻 Practical Program
📘 Step Learning
This program asks user to enter a string and a character and checks how many times the character is repeated in the string.

💻 Program Code

#include <stdio.h>

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

   printf("Enter a string: ");
   gets(str);

   printf("Enter a character to find the frequency: ");
   scanf("%c",&ch);

   for(i = 0; str[i] != '\0'; ++i)
   {
       if(ch == str[i])
           ++frequency;
   }

   printf("Frequency of %c = %d", ch, frequency);

   return 0;
}
                        

🖥 Program Output

Enter a string: This website is awesome.
Enter a character to find the frequency: e
Frequency of e = 4
                            

📘 Explanation

This program asks user to enter a string and a character and checks how many times the character is repeated in the string.


In this program, the string entered by the user is stored in variable str.

Then, the user is asked to enter the character whose frequency is to be found. This is stored in variable ch.

Now, using the for loop, each character in the string is checked for the entered character.

If, the character is found, the frequency is increased. If not, the loop continues.

Finally, the frequency is printed.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.