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.

Example:
Input any string: I love CodeforWin!
Output maximum occurring character: 'o'

Required knowledge

Basic C programming, Loop, Array, String

Logic to find maximum occurring character in string

Logic to this program is simple and involves basic two tasks:
  1. Find frequency of each characters in the string and store it in some array of integers.
  2. Find maximum element in the array. Maximum element in the array will the be maximum occurring character in the string.


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 size of the string
#define MAX_CHARS 255 //Maximum characters allowed


int main()
{
    char string[MAX_SIZE];
    int frequency[MAX_CHARS]; //Stores frequency of each character
    int i = 0, max;
    int ascii;

    printf("Enter any string: ");
    gets(string);

    /* Initializes frequency of all characters to 0 */
    for(i=0; i<MAX_CHARS; i++)
    {
        frequency[i] = 0;
    }


    /* Finds frequency of each characters */
    i=0;
    while(string[i] != '\0')
    {
        ascii = (int)string[i];
        frequency[ascii] += 1;

        i++;
    }


    /* Finds maximum frequency */
    max = 0;
    for(i=0; i<MAX_CHARS; i++)
    {
        if(frequency[i] > frequency[max])
            max = i;
    }


    printf("Highest frequency of '%c' is %d.\n", max, frequency[max]);

    return 0;
} 


Output
Enter any string: I love CodeforWin!
Highest frequency of 'o' is 3.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment