Highest frequency character in string c program

This program will find the character with highest occurrence in string. If there are two or more character with highest and same frequency in string then program will print alphabetically first character in string. For example if string is "programmingside". Here 'g', 'r', 'm', 'i' occurring  two times so program will print 'g'.

C Program: 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 256
 
/* Functio to get character count array */
int *CharCountArray(char *str)
{
	int i;
 
	int *count=(int*)calloc(sizeof(int),SIZE);
 
	for(i=0;*(str+i);i++)
	{
		count[str[i]]++;
	}
 
	return count;
}
void MaxFrequency(char *str)
{
 
	int index,max=0,i,n=strlen(str);
 
	int *count=CharCountArray(str);
 
	for(i=0;i<256;i++)
	{
		if(max<count[i])
		{
			max=count[i];
			index = i;
		}
	}
 
	printf("Max frequency => %c = %d",index,max);
 
}
int main()
{
	char str[100];
 
	printf("Enter a string: ");
	scanf("%s",str);
 
	MaxFrequency(str);
 
	return 0;
}

Time Complexity of this program will be O(n).

Another simple program without pointer

#include<stdio.h>
#include<string.h>
 
void MaxFrequency(char str1[])
{
	int count[256]={0};
 
	int index,max=0,i,n=strlen(str1);
 
	for(i=0;i<n;i++)
	{
		count[str1[i]]++;
	}
 
	for(i=0;i<256;i++)
	{
		if(max<count[i])
		{
			max=count[i];
			index = i;
		}
	}
 
	printf("Max frequency => %c = %d",index,max);
 
}
int main()
{
	char str[100];
 
	printf("Enter a string: ");
	scanf("%s",str);
 
	MaxFrequency(str);
 
	return 0;
}




Popular posts from this blog