Home / Programs / Frequency of Characters in a String using C Programming Language
🚀 Programming Example

Frequency of Characters in a String using C Programming Language

👁 415 Views
💻 Practical Program
📘 Step Learning

Frequency of Characters in a String using C Programming Language

To understand this example, you should have the knowledge of the following C programming topics:

  • C Arrays
  • C Programming Strings

💻 Program Code

#include<stdio.h>
#include<string.h>
int main()
{
int i, count = 0;
char arrayName[100], ch;

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

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

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

 printf("Frequency of %c = %d", ch, count);
 return 0;
}

                        

🖥 Program Output

Enter a string: Rumman Ansari
Enter a character to find its frequency: m
Frequency of m = 2
                            

📘 Explanation

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

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

Then, a for loop is used to iterate over characters of the string. In each iteration, if the character in the string is equal to the chcount is increased by 1.

Finally, the frequency stored in the count variable 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.