In this tutorial, you will learn how to write a C program to find the frequency of characters in a string. We will see two programs. The first program prints the frequency of specified character. In the second program, we are printing the frequency of each character in a string.
Example 1: Program to find frequency of a character in a String
In this program, user is asked to enter a string. This input string is read and stored in a char array str. User is asked again to enter the character to find its frequency in the input string. This character is stored in char variable ‘ch’.
A loop runs from from first element of the array till the end of the string (‘\0’ is the end of the string). Each element of the array is compared with ch, if match is found, the value of variable count is increased. At the end of the loop, the value of the count represents the frequency of the input character in string.
#include <stdio.h>
int main() {
char str[250], ch;
int count = 0;
//User input the string
printf("Enter any string: ");
fgets(str, sizeof(str), stdin);
//User enters a character to find its frequency
printf("Enter a character: ");
scanf("%c", &ch);
//'\0' represents the end of string
for (int i = 0; str[i] != '\0'; ++i) {
if (ch == str[i])
++count;
}
printf("Frequency of character %c in string is: %d", ch, count);
return 0;
}
Output:
C Program to find frequency of each character in a String
Here we are displaying the frequency of each character in a string. The logic is same as the first program except that here we are displaying frequency of all characters.
#include <stdio.h>
int main()
{
char str[250];
int i,j,count=0,size=0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
//'\0' represents the end of string
for (int i = 0; str[i] != '\0'; ++i) {
++size;
}
printf("Frequency of each character in string:\n");
for(i=0;i<size;i++)
{
count=1;
if(str[i])
{
for(j=i+1;j<size;j++)
{
if(str[i]==str[j])
{
count++;
str[j]='\0';
}
}
printf("Frequency of char '%c' is: %d \n",str[i],count);
}
}
return 0;
}
Output: