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 by 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;
}

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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.