Frequency of Characters in a String using C Programming Language

C Programming Language String functions in C (Article) String functions in C (Program)

309

Program:

#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.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.