C Program to Find the Frequency of Characters in a String

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


Find the Frequency of a Character

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

Output

Enter a string: This website is awesome.
Enter a character to find its frequency: e
Frequency of e = 4

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

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 ch, count is increased by 1.

Finally, the frequency stored in the count variable is printed.

Note: This program is case-sensitive i.e. it treats uppercase and lowercase versions of the same alphabet as different characters.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges