w3resource

C Programming: Find the Frequency of Characters

C String: Exercise-18 with Solution

Write a program in C to find the frequency of characters.

C Programming: Find the Frequency of Characters

Sample Solution:

C Code:

#include <stdio.h>

int main() {
    char str[1000], choice; // Declare a character array to store the string and a variable for the character to find frequency
    int i, ctr = 0; // Declare variables for iteration and counting frequency

    printf("\n\nFind the Frequency of Characters :\n"); // Display information about the task
    printf("--------------------------------------\n");

    printf("Input the string : ");
    fgets(str, sizeof str, stdin); // Read a string from the standard input (keyboard)

    printf("Input the character to find frequency: ");
    scanf("%c", &choice); // Read the character for which frequency needs to be found

    for (i = 0; str[i] != '\0'; ++i) {
        if (choice == str[i]) { // Check if the character matches the current character in the string
            ++ctr; // Increment the counter if the character matches
        }
    }
    printf("The frequency of '%c' is : %d\n\n", choice, ctr); // Display the frequency of the chosen character
	
	return 0; // Return 0 to indicate successful execution of the program
}

Sample Output:

Find the Frequency of Characters :                                                                                            
--------------------------------------                                                                                        
Input the string : This is a test string                                                                                      
Input the character to find frequency: i                                                                                      
The frequency of 'i' is : 3

Flowchart :

Flowchart: Find the Frequency of Characters

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a program in C to remove characters in String Except Alphabets.
Next: Write a program in C to Concatenate Two Strings Manually.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/string/c-string-exercise-18.php