Write a C program to find maximum occurring character in a string using loop. How to find highest frequency character in a string using loop in C programming. Program to find the highest occurring character in a string in C. Logic to find maximum occurring character in a string in C programming.
Example
Input
Input string: I love Codeforwin.
Output
Maximum occurring character: 'o'
Required knowledge
Basic C programming, Loop, Array, String
Must know –
Logic to find maximum occurring character in string
Below is the step by step descriptive logic to find maximum occurring character in a string.
- Input string from user, store it in some variable say str.
- Declare another array to store frequency of all alphabets, say freq[26]. I have declared size of freq as 26 since there are 26 alphabets in English.
- Initialize frequencies of all alphabets in freq array to 0.
- Find frequency of each character present in the string.
- Maximum occurring character in string is maximum occurring value in the freq array.
Program to find maximum occurrence of a character
/**
* C program to find maximum occurring character in a string
*/
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
#define MAX_CHARS 255 // Maximum characters allowed
int main()
{
char str[MAX_SIZE];
int freq[MAX_CHARS]; // Store frequency of each character
int i = 0, max;
int ascii;
printf("Enter any string: ");
gets(str);
/* Initializes frequency of all characters to 0 */
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
/* Finds frequency of each characters */
i=0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1;
i++;
}
/* Finds maximum frequency */
max = 0;
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] > freq[max])
max = i;
}
printf("Maximum occurring character is '%c' = %d times.", max, freq[max]);
return 0;
}
Read more – Program to find minimum occurring character in a string
Output
Enter any string: I love Codeforwin. Maximum occurring character is 'o' = 3 times.
Happy coding 😉
Recommended posts
- String programming exercises index.
- C program to find first occurrence of a character in a string.
- C program to find last occurrence of a character in a string.
- C program to search all occurrences of a character in a string.
- C program to remove first occurrence of a character in a string.
- C program to remove last occurrence of a character in a string.
- C program to remove all occurrences of a character in a string.
- C program to count occurrences of a character in a string.