C Program to Find the Frequency of Characters in a String using Arrays
ADVERTISEMENTS
C Program to Find the Frequency of Characters in a String using Arrays.
In this article, you will learn how to find the frequency of the input characters from the given sentence using the for loop & Arrays.
Example
Enter the string: hi this is my first program
Enter a character to count it's frequency: h
Frequency of 'h' is 2
Enter a character to count it's frequency: h
Frequency of 'h' is 2
You should know about the following topics in C programming to understand this program:
- C For Loop
- C Arrays
Source
// C Program to Find the Frequency of Characters in a String
#include <stdio.h>
// It's the main function of the program
int main() {
char string[500], search_char;
int string_count = 0;
// Step-1 Take input any sentence up to 500 characters
printf("Enter the string: ");
fgets(string, sizeof(string), stdin);
// Step-2 Enter a character to find
printf("Enter a character to count it's frequency: ");
scanf("%c", &search_char);
// Step-3 Make iteration over the given sentence
for (int i = 0; string[i] != '\0'; i++) {
if (string[i] == search_char) {
string_count += 1;
}
}
// Step-4 Final output of the program
printf("Frequency of '%c' is %d\n", search_char, string_count);
return 0;
}
Output
Enter the string: hi this is my first program
Enter a character to count it's frequency: i
Frequency of 'i' is 4