C program to find maximum occurring character in a string

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.

  1. Input string from user, store it in some variable say str.
  2. 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.
  3. Initialize frequencies of all alphabets in freq array to 0.
  4. Find frequency of each character present in the string.
  5. 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 😉