w3resource

C Programming: Find the Frequency of Characters


18. Frequency of a Character

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
}

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


For more Practice: Solve these Related Problems:

  • Write a C program to count the number of times a given character appears in a string using pointer arithmetic.
  • Write a C program to compute the frequency of a specific character without using any library functions.
  • Write a C program to determine the percentage occurrence of a character in a string.
  • Write a C program to count a character's frequency recursively and output the result.

Go to:


PREV : Remove Non-Alphabets.
NEXT : Concatenate Strings Manually.

C Programming Code Editor:



Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.