C program to find the frequency of characters in a string
C program to find the frequency of characters in a string: This program counts the frequency of characters in a string, i.e., which character is present how many times in the string. For example, in the string “code” each of the characters ‘c,’ ‘d,’ ‘e,’ and ‘o’ has occurred one time. Only lower case alphabets are considered, other characters (uppercase and special characters) are ignored. You can modify this program to handle uppercase and special symbols.
C programming code
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int c = 0, count[26] = {0}, x;
printf(“Enter a string\n“);
gets(string);
while (string[c] != ‘\0‘) {
/** Considering characters from ‘a’ to ‘z’ only and ignoring others. */
if (string[c] >= ‘a’ && string[c] <= ‘z’) {
x = string[c] – ‘a’;
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
printf(“%c occurs %d times in the string.\n“, c + ‘a’, count[c]);
return 0;
}
Explanation of “count[string-‘a’]++”, suppose input string begins with ‘a’ so c is 0 initially and string[0] = ‘a’ and string[0] – ‘a’ = 0 and we increment count[0], i.e., ‘a’ has occurred one time and repeat this until the complete string is scanned.
Output of program:
Did you notice that the string in the output of the program contains every alphabet at least once?
Calculating frequency using function
We will make a function which computes frequency of characters in input string and print it in a table (see output image below).
#include <stdio.h>
#include <string.h>
void find_frequency(char [], int []);
int main()
{
char string[100];
int c, count[26] = {0};
printf(“Input a string\n“);
gets(string);
find_frequency(string, count);
printf(“Character Count\n“);
for (c = 0 ; c < 26 ; c++)
printf(“%c \t %d\n“, c + ‘a’, count[c]);
return 0;
}
void find_frequency(char s[], int count[]) {
int c = 0;
while (s[c] != ‘\0‘) {
if (s[c] >= ‘a’ && s[c] <= ‘z’ )
count[s[c]–‘a’]++;
c++;
}
}
Output of the program:
We do not pass no of elements of array count[] to function find_frequency as they will always be 26 if considering only lower case alphabets. But you can pass if you wish to do so.