// Timothy Price CS1A Ch 10 Challenge 9
/******************************************************************************
* Determine most frequent character
*
* This program receives a set of character and determines the most
* frequently used character.
*
* Input:
* a word or sentence(s)
*
* Output:
* the most frequently used character
******************************************************************************/
#include <cctype>
#include <iostream>
using namespace std;
// Function prototype
char mostFrequentChar(const char* str);
int main()
{
// Data dictionary
const int MAX_LENGTH = 256;
char input[MAX_LENGTH];
// Receive input and output confirmation
cout << "Most Frequent Character Finder" << endl;
cout << "----------------------------------------" << endl;
cout << "Enter a string: ";
cin.getline(input, MAX_LENGTH);
cout << input << endl;
// Call function
char frequent = mostFrequentChar(input);
if (frequent == '\0')
{
cout << "No non-space characters found." << endl;
}
else
{
cout << "Most frequent character: '" << frequent << "'" << endl;
}
return 0;
}
// Function definition
char mostFrequentChar(const char* str)
{
const int ASCII_SIZE = 256;
int counts[ASCII_SIZE] = {0};
if (str == nullptr || *str == '\0')
{
return '\0';
}
const char* current = str;
while (*current != '\0')
{
unsigned char raw = static_cast<unsigned char>(*current);
if (!isspace(raw))
{
unsigned char normalized =
static_cast<unsigned char>(tolower(raw));
counts[normalized]++;
}
current++;
}
int maxCount = 0;
char bestChar = '\0';
// Scan in original string order so ties keep the earlier character
current = str;
while (*current != '\0')
{
unsigned char raw = static_cast<unsigned char>(*current);
if (!isspace(raw))
{
unsigned char normalized =
static_cast<unsigned char>(tolower(raw));
if (counts[normalized] > maxCount)
{
maxCount = counts[normalized];
bestChar = static_cast<char>(normalized);
}
}
current++;
}
return bestChar;
}