Advertisement
Porr011

Lesson 11 activity 2

Mar 18th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. //function prototype
  6. void calculateMode(int [], int );
  7.  
  8. //**************
  9. //*Main function
  10. //* has getting text file then storing into array and then function to finding the mode
  11. //************
  12. int main ()
  13. {
  14.     const int ARRAY_SIZE = 50; // constant so we can use it outside of main
  15.     int numbers [ARRAY_SIZE];
  16.     int count = 0; // loop counter varible
  17.     ifstream inputFile; // input file stream object
  18.    
  19.     //opening the file
  20.     inputFile.open("file.txt");
  21.    
  22.     //reading the numbers from the file then putting it into the array
  23.     while (count < ARRAY_SIZE && inputFile >> numbers [count])
  24.     count ++;
  25.    
  26.     // closing file
  27.     inputFile.close();
  28.    
  29.     // calling on our function for calculating mode
  30.     calculateMode(numbers, ARRAY_SIZE);
  31.    
  32.     return 0;
  33. }
  34.  
  35. //*********
  36. //* Calculating the mode funtion
  37. //* calculates mode and then displays it
  38. //*********
  39. void calculateMode(int ARRAY_SIZE[], int size)
  40. {
  41.       int MODE_COUNTER[100] = { 0 }; // since my values are allways like 0-99
  42.         int mode = 0;
  43.         int max = 0;
  44.  
  45.         for (int i = 0; i < size; i++) // finding the mode using index
  46.             if (++MODE_COUNTER[ARRAY_SIZE[i]] > max)
  47.             // for loop for finding the number that is most frequent
  48.             {
  49.                 mode = ARRAY_SIZE[i];
  50.                 max = MODE_COUNTER[ARRAY_SIZE[i]];
  51.             }
  52.  
  53.         cout << "The mode is " << mode << endl; // cout the mode
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement