C Program to Find the Frequency of Characters in a String

C Examples Sort Elements in Lexicographical Order (Dictionary Order) Copy String Without Using strcpy() Concatenate Two Strings Find the Length of a

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

·       C Arrays

·       C Multidimensional Arrays

·       Pass arrays to a function in C

·       C for Loop

·       C Arrays

·       C Pointers

·       Relationship Between Arrays and Pointers

·       C Pointers

·       C Pass Addresses and Pointers

·       C Dynamic Memory Allocation


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

Labels : #c ,#code ,#examples ,

Post a Comment