Hello. I am working on an assignment for my c++ class and I need to write a program that accepts a c-string and sends it to a function that finds the most frequently occurring character. I followed some directions I found online and the program will compile but I am having trouble getting it to display the most frequent character. If somebody could point out the problem in my code it would be much appreciated. Thanks!
//Most Frequent Character
#include<iostream>
#include<cstring>
usingnamespace std;
char mostFrequent(char*, int);
int main()
{
constint size=50;
char string1[size];
cout<<"Enter a string up to 50 characters and I will find the most frequent character.\n";
cin.getline(string1, size);
char mostFrequentCharacter=mostFrequent(string1, size);
cout<<"The most frequent character in the string is: "<<mostFrequentCharacter<<".\n";
return 0;
}
char mostFrequent(char* string1, int size)
{
int array[255]={0};
int i=0;
int max=0;
int index=0;
for(i=0; string1[i]!=0; i++)
{
++array[string1[i]];
}
max=array[0];
for(i=0; string1[i]!=0; i++)
{
if(array[i]>max)
{
max=array[i];
index=i;
}
}
char mostCommon=(char)index;
return mostCommon;
}