C Example for Beginners: C Program to Find the Frequency of Characters in a String

Hits: 12

(C programming Example for Beginners)

C Program to Find the Frequency of Characters in a String

In this example, you will learn to find the frequency of a character in a string.


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] != ''; ++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.

 

C Example for Beginners: C Program to Find the Frequency of Characters in a String

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.