fork download
  1. // Timothy Price CS1A Ch 10 Challenge 9
  2. /******************************************************************************
  3.  * Determine most frequent character
  4.  *
  5.  * This program receives a set of character and determines the most
  6.  * frequently used character.
  7.  *
  8.  * Input:
  9.  * a word or sentence(s)
  10.  *
  11.  * Output:
  12.  * the most frequently used character
  13. ******************************************************************************/
  14. #include <cctype>
  15. #include <iostream>
  16.  
  17. using namespace std;
  18.  
  19. // Function prototype
  20. char mostFrequentChar(const char* str);
  21.  
  22. int main()
  23. {
  24. // Data dictionary
  25. const int MAX_LENGTH = 256;
  26. char input[MAX_LENGTH];
  27.  
  28. // Receive input and output confirmation
  29. cout << "Most Frequent Character Finder" << endl;
  30. cout << "----------------------------------------" << endl;
  31. cout << "Enter a string: ";
  32. cin.getline(input, MAX_LENGTH);
  33. cout << input << endl;
  34.  
  35. // Call function
  36. char frequent = mostFrequentChar(input);
  37.  
  38. if (frequent == '\0')
  39. {
  40. cout << "No non-space characters found." << endl;
  41. }
  42. else
  43. {
  44. cout << "Most frequent character: '" << frequent << "'" << endl;
  45. }
  46.  
  47. return 0;
  48. }
  49.  
  50. // Function definition
  51. char mostFrequentChar(const char* str)
  52. {
  53. const int ASCII_SIZE = 256;
  54. int counts[ASCII_SIZE] = {0};
  55.  
  56. if (str == nullptr || *str == '\0')
  57. {
  58. return '\0';
  59. }
  60.  
  61. const char* current = str;
  62. while (*current != '\0')
  63. {
  64. unsigned char raw = static_cast<unsigned char>(*current);
  65.  
  66. if (!isspace(raw))
  67. {
  68. unsigned char normalized =
  69. static_cast<unsigned char>(tolower(raw));
  70. counts[normalized]++;
  71. }
  72.  
  73. current++;
  74. }
  75.  
  76. int maxCount = 0;
  77. char bestChar = '\0';
  78.  
  79. // Scan in original string order so ties keep the earlier character
  80. current = str;
  81. while (*current != '\0')
  82. {
  83. unsigned char raw = static_cast<unsigned char>(*current);
  84.  
  85. if (!isspace(raw))
  86. {
  87. unsigned char normalized =
  88. static_cast<unsigned char>(tolower(raw));
  89.  
  90. if (counts[normalized] > maxCount)
  91. {
  92. maxCount = counts[normalized];
  93. bestChar = static_cast<char>(normalized);
  94. }
  95. }
  96.  
  97. current++;
  98. }
  99.  
  100. return bestChar;
  101. }
Success #stdin #stdout 0s 544KB
stdin
hello world
stdout
Most Frequent Character Finder
----------------------------------------
Enter a string: hello world
Most frequent character: 'l'