/* Most Frequent Character - This program contains a function that accepts
a string object as its argument. The function returns the character that
appears most frequently in the string. */
#include "Utility.h"
/* Finds the most frequently occuring character in the string,
stores the frequency in a reference variable, returns the
most frequently occuring character */
char mostFreq(string, unsigned int &);
int main()
{
unsigned int frequency = 0;
char mostFreqChar = ' ';
string sentence = " ";
cout << "\n\tMost Frequent Character\n\n"
<< "\tEnter a sentence, and I will show you, what the most\n"
<< "\tfrequently occuring character is.\n\n"
<< "\tPlease enter your sentence: ";
getline(cin, sentence);
mostFreqChar = mostFreq(sentence, frequency);
cout << "\n\tThe most frequent character is "
<< '\'' << mostFreqChar << '\'' << ", appearing "
<< frequency << " times in your sentence.";
pauseSystem();
return 0;
}
/* **********************************************************
Definition: mostFreq
This function accepts a string class object as argument.
It determines the most frequently appearing character in
the string and returns it. The frequency in which this
character appears is stored in a reference variable.
********************************************************** */
char mostFreq(string sentence, unsigned int &frequency)
{
unsigned int index = 0,
startScan = 0,
charCount = 0;
char mostFreqChar = ' ';
for (startScan = index + 1; startScan < sentence.size(); startScan++)
{
charCount = 0;
for (index = 0; index < sentence.size(); index++)
{
if (isalpha(sentence[index]) && isalpha(sentence[startScan]))
{
if (tolower(sentence[startScan]) == tolower(sentence[index]))
{
charCount++;
}
if (charCount > frequency)
{
frequency = charCount;
mostFreqChar = (tolower(sentence[index]));
}
}
}
}
return mostFreqChar;
}
Sunday, April 23, 2017
Programming Challenge 10.9 - Most Frequent Character
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment