Find the Frequency of Characters in a String in C

Exercise:

Write a C Program to find the frequency of characters in a string.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    char str[1000], ch;
    int count = 0;
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    printf("Enter a character to find its frequency: ");
    scanf("%c", &ch);
    for (int i = 0; str[i] != '\0'; ++i) {
        if (ch == str[i]) {
            ++count;
        }
    }
    printf("Frequency of %c = %d", ch, count);
    return 0;
}
Click Here to View the Output!
Enter a string: java
Enter a character to find its frequency: a
Frequency of a = 2
Click Here to View the Explanation!
  • This program is used to determine the frequency of a character in a string.
  • In main(), a string array str is declared of the size 1000 and a variable ch.
  • The program requests the user to enter a string and stores it in str.
  • The program then requests the user to enter a character of which they want to find the frequency of in the string and stores it in the variable ch using the scanf() function.
  • A for loop is initialized which iterates over the character in the string until str[i] is not equal to 0.
  • In an if statement, the ch is compared with every character in the string and if (ch == str[i]), the value of count is incremented by 1.
  • The frequency of the character is therefore, stored in the variable count which is then displayed on the screen.
%d bloggers like this: