Max frequency of character

#include
#include
using namespace std;

int main()

{

string s;
getline(cin,s);
int frearr[50]={0};
char ch=' ';
int maxfre=0;
for(int i=0;i<s.length();i++)
{
	frearr[s[i]]++;
}
for(int i=0;i<s.length();i++)
{
    if(frearr[i]>maxfre)
    {
        maxfre=frearr[i];
        ch=s[i];
    }
    cout<<ch;
}
return 0;

}

here is my solution . Its not printing anything

@ritik_99
The ASCII value of character ‘a’ is 97. The ASCII value of further alphabet characters is obviously higher. Your array cannot accomodate them as it is of size 50. Hence the problem.

but here the integer array is used to store frequency of each character not the character ascii code. And what does the size of character has to do with ascii code. ? here int arr is storing frequency

@ritik_99
When you do freq[‘a’]++ , compiler interpretes it as freq[97]++. You can’t store the frequency of characters if you do not have their indices in your array.

frearr[s[i]] ++ means i am updating the index at which s[i] character is present in the frearr array. The program is compiling succesfully but only the output is not coming why it is that when i have given cout command also

@ritik_99
I know what frearr[s[i]] ++ means. And you seem to be saying the same thing as well, but still your implementation is wrong. It will only update the index at which s[i] character is present if that index exists in your array. Your array is of size 50 and it is trying to access 97th index for character ‘a’. Similarly it will try to access index 122 for ‘z’ , both of which are out of bounds.
There will be no problem in compiling since this is a runtime problem.

Also , your code is giving an output, the cout statement is working. Just not how you want it to because of the above mentioned problem.
Your ch is initialised to a blank space. It is never updated because the if condition would never work and hence your code prints a blank space only as final output.
Try initialising your ch as some character , say ch=‘x’. And then give a string as input which doesn’t contain an ‘x’ at all. Try your code then.

ok. So what i need to update to get my code right ?

@ritik_99
One solution would be to increase your array size to 256 to account for all characters in ASCII.

ya what else ? only updating array to 256 wont do the work ? suggest me all the changes required plz ?

@ritik_99
Well then there’s the obvious change that the cout statement should be outside the loop. Apart from these two, I think it should work. Try it out.

doing so also does not work . same blank output

@ritik_99
Share your latest code here by saving it on the IDE.

Its working now , thanks

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.