Home »
C programs »
C string programs
C program to find the highest frequency of a character in the given string
Here, we are going to learn how to find the highest frequency of a character in the given string in C programming language?
Submitted by Nidhi, on July 20, 2021
Problem Solution:
Read a string from the user and find the highest frequency of a character in the given string using C program.
Program:
The source code to find the highest frequency of a character in the given string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to find the highest frequency of a character
// in the given string
#include <stdio.h>
#include <string.h>
void printHighestFrequency(char* str)
{
int i = 0;
int j = 0;
int k = 0;
int len = 0;
int high = 0;
int index = 0;
int flag = 0;
char str1[64];
int cnt[64] = { 0 };
len = strlen(str);
while (i < len) {
if (i == 0) {
str1[j++] = str[i];
cnt[j - 1]++; // = cnt[j - 1] + 1;
}
else {
for (k = 0; k < j; k++) {
if (str[i] == str1[k]) {
cnt[k]++;
flag = 1;
}
}
if (flag == 0) {
str1[j++] = str[i];
cnt[j - 1]++;
}
flag = 0;
}
i++;
}
for (i = 0; i < j; i++) {
if ((i == 0) && (str1[i] != ' ')) {
high = cnt[i];
continue;
}
if ((high < cnt[i]) && (str1[i] != ' ')) {
high = cnt[i];
index = i;
}
}
printf("Character '%c' is repeted %d time\n", str1[index], cnt[index]);
}
int main()
{
char str[64];
printf("Enter the string: ");
scanf(" %[^\n]s", str);
printHighestFrequency(str);
return 0;
}
Output:
RUN 1:
Enter the string: this is india.
Character 'i' is repeted 4 time
RUN 2:
Enter the string: is are am
Character 'a' is repeted 2 time
RUN 3:
Enter the string: Hello world, how are you?
Character 'o' is repeted 4 time
Explanation:
In the above program, we created two functions printHighestFrequency() and main(). The printHighestFrequency() function is used to find the highest frequency character in string.
In the main() function, we read a string from the user and called the printHighestFrequency() function and printed the highest frequency character in the string on the console screen.
C String Programs »