fork download
  1. //Ryan Shahriyarpour CS1A Chapter 9 Question 8
  2. /*****************************************************************************
  3.  *
  4.  * Find the Mode of an Array
  5.  *
  6.  *********************
  7.  *
  8.  * This program finds the mode of a set of nonnegative integers, which is the
  9.  * value that occurs most often. If no value occurs more than once, there is
  10.  * no mode and the result is -1. The program displays the mode of two test
  11.  * arrays.
  12.  *
  13.  * INPUT
  14.  * None (the test arrays are set in the program)
  15.  *
  16.  * OUTPUT
  17.  * The mode of each test array (-1 means no mode)
  18.  *
  19.  ****************************************************************************/
  20.  
  21. #include <iostream>
  22. using namespace std;
  23.  
  24. const int SIZE1 = 8; // Number of elements in the first array
  25. const int SIZE2 = 5; // Number of elements in the second array
  26.  
  27. // Function prototype
  28. int getMode(const int *array, int size);
  29.  
  30. int main()
  31. {
  32. // data dictionary
  33. int set1[SIZE1] = {2, 4, 7, 4, 1, 9, 4, 2}; // Array with a mode
  34. int set2[SIZE2] = {10, 20, 30, 40, 50}; // Array with no mode
  35. int mode1; // Mode of set1
  36. int mode2; // Mode of set2
  37.  
  38. mode1 = getMode(set1, SIZE1);
  39. mode2 = getMode(set2, SIZE2);
  40.  
  41. cout << "Mode of set 1: " << mode1 << endl;
  42. cout << "Mode of set 2: " << mode2 << " (-1 means no mode)" << endl;
  43.  
  44. return 0;
  45. }
  46.  
  47. // Returns the mode of the array, or -1 if there is no mode
  48. int getMode(const int *array, int size)
  49. {
  50. int mode = -1; // Value with the highest count so far
  51. int highest = 1; // Highest count so far
  52. int outer; // Loop counter for the value being counted
  53. int inner; // Loop counter for scanning the array
  54. int count; // Times the current value appears
  55.  
  56. for (outer = 0; outer < size; outer++)
  57. {
  58. count = 0;
  59. for (inner = 0; inner < size; inner++)
  60. {
  61. if (*(array + inner) == *(array + outer))
  62. count++;
  63. }
  64. if (count > highest)
  65. {
  66. highest = count;
  67. mode = *(array + outer);
  68. }
  69. }
  70. return mode;
  71. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Mode of set 1: 4
Mode of set 2: -1  (-1 means no mode)