In: Computer Science
use C++
Example of Output:
letters |
frequency |
a |
10 |
b |
4 |
c |
6 |
v |
12 |
s |
20 |
z |
1 |
r |
3 |
Letter s has the highest frequency of 20.
Code is
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
int i, len;
// declare a array to store frequency of each character
int freq[26];
/* Input string from user */
cout<<"Enter any string: (atleast 50
characters)";
getline(cin,s);
len = s.size();
/* Initialize frequency of each character to 0 */
for(i=0; i<26; i++)
{
freq[i] = 0;
}
/* Find total number of occurrences of each character */
for(i=0; i<len; i++)
{
/* If the current character is lowercase alphabet */
if(s[i]>='a' && s[i]<='z')
{
freq[(int)s[i] - 97]++;
}
// else upper case
else if(s[i]>='A' && s[i]<='Z')
{
freq[(int)s[i] - 65]++;
}
}
// To get max frequent letter use a loop
int max=freq[0],maxposition;
for(int i=1;i<26;i++)
{
if(freq[i]>max)
{
max = freq[i];
maxposition=i;
}
}
/* Print the frequency of all characters in the string */
cout<<"\nFrequency of all characters in the given
string: \n";
cout<<"Letter \t frequency\n";
for(i=0; i<26; i++)
{
/* If current character exists in given string */
if(freq[i] != 0)
{
cout<<(char)(i + 97)<<" \t"<<
freq[i]<<endl;
}
}
cout<<"Letter
"<<(char)(maxposition+97)<<" has the highest frequency
of "<<max;
return 0;
}
Code Screen Shot
Output
This is how you can write a program in C++ to get frequency of each characters in string s
If u like the answer then Give It a Thumbs Up and have any doubt comment it