Write a C Program to Find Frequency of each Character in a String with example.
C Program to Find Frequency of each Character in a String Example 1
This program allows the user to enter a string (or character array). Next, it will find the frequency of every character present in this string.
#include <stdio.h> #include <string.h> int main() { char str[100]; int i; int freq[256] = {0}; printf("\n Please Enter any String : "); gets(str); for(i = 0; str[i] != '\0'; i++) { freq[str[i]]++; } for(i = 0; i < 256; i++) { if(freq[i] != 0) { printf("Character '%c' Occurs %d Times \n", i, freq[i]); } } return 0; }
Program to Find Frequency of each Character in a String Example 2
This character frequency program is the same as above, but we made small changes to the C Programming logic.
/* C Program to Find Frequency of each Character in a String */ #include <stdio.h> #include <string.h> int main() { char str[100]; int i; int freq[26] = {0}; printf("\n Please Enter any String : "); gets(str); for(i = 0; str[i] != '\0'; i++) { if(str[i] >= 'a' && str[i] <= 'z') { freq[str[i] - 'a']++; } else if(str[i] >= 'A' && str[i] <= 'Z') { freq[str[i] - 'A']++; } } for(i = 0; i < 26; i++) { if(freq[i] != 0) { printf("Character '%c' Occurs %d Times \n", i+'a', freq[i]); } } return 0; }
Please Enter any String : Tutorial Gateway
Character 'a' Occurs 3 Times
Character 'e' Occurs 1 Times
Character 'g' Occurs 1 Times
Character 'i' Occurs 1 Times
Character 'l' Occurs 1 Times
Character 'o' Occurs 1 Times
Character 'r' Occurs 1 Times
Character 't' Occurs 3 Times
Character 'u' Occurs 1 Times
Character 'w' Occurs 1 Times
Character 'y' Occurs 1 Times
Example 3
This Character frequency program is the same as the second example, but this time we used the Functions concept to separate the logic.
#include <stdio.h> #include <string.h> void Freq_eachCharacter(char *str); int main() { char str[100]; printf("\n Please Enter any String : "); gets(str); Freq_eachCharacter(str); return 0; } void Freq_eachCharacter(char *str) { int i; int freq[26] = {0}; for(i = 0; str[i] != '\0'; i++) { if(str[i] >= 'a' && str[i] <= 'z') { freq[str[i] - 'a']++; } else if(str[i] >= 'A' && str[i] <= 'Z') { freq[str[i] - 'A']++; } } for(i = 0; i < 26; i++) { if(freq[i] != 0) { printf("Character '%c' Occurs %d Times \n", i+'a', freq[i]); } } }
Please Enter any String : C Programming
Character 'a' Occurs 1 Times
Character 'c' Occurs 1 Times
Character 'g' Occurs 2 Times
Character 'i' Occurs 1 Times
Character 'm' Occurs 2 Times
Character 'n' Occurs 1 Times
Character 'o' Occurs 1 Times
Character 'p' Occurs 1 Times
Character 'r' Occurs 2 Times