Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. int calMode (int [], int arrSize); //function to calculate the mode
  8.  
  9. int main() {
  10.     ifstream myfile("info.txt");
  11.    
  12.     // stating variables
  13.    
  14.     string w;
  15.     string x;
  16.     int y;
  17.    
  18.     //using getline here to get the first number of the array transform it into an int using stoi(x) and pluging it into arrSize
  19.     getline(myfile, x);
  20.     int arrSize = 0;
  21.     y = stoi(x);
  22.        
  23.     int arr[y];
  24.    
  25.     //if statement for opening the info.txt file
  26.    
  27.     if (myfile.is_open())
  28.     {
  29.        
  30.     //while loop that gets the information from the info.txt file and puts it into the array
  31.  
  32.         while (!myfile.eof())
  33.         {
  34.             int f;
  35.             myfile >> f;
  36.             arr[arrSize++] = f;
  37.         }
  38.         for (int i = 0; i < arrSize ; ++i)
  39.             cout << arr[i] << " ";
  40.         cout << endl;
  41.        
  42.        
  43.     }
  44.    
  45.     //calling the function that calculates the mode
  46.        
  47.     calMode(arr, arrSize);
  48.    
  49.     return 0;
  50. }
  51.  
  52. /****
  53. * Calculates mode and displays it
  54. * @param - arr[]
  55. * @param - arrSize
  56. * @return - void  
  57. ****/
  58.    
  59. int calMode(int arr[], int arrSize)
  60. {
  61.    
  62.     //for loop that creates arrays of the array and compares both arrays to find the mode
  63.     int* mode = new int[arrSize];
  64.     for (int i = 0; i < arrSize; ++i) {
  65.         mode[i] = 0;
  66.         int j = 0;
  67.        
  68.     //declaration of boolean statement to stop/continue function
  69.    
  70.         bool bFound = false;
  71.         while ((j < i) && (arr[i] != arr[j])) {
  72.             if (arr[i] != arr[j]) {
  73.                 ++j;
  74.             }
  75.         }
  76.        
  77.     //increases the array mode to compare it with the other array
  78.    
  79.         ++(mode[j]);
  80.     }
  81.     int iMaxRepeat = 0;
  82.     for (int i = 1; i < arrSize; ++i) {
  83.         if (mode[i] > mode[iMaxRepeat]) {
  84.             iMaxRepeat = i;
  85.         }
  86.     }
  87.    
  88.     //cout statement that shows the mode
  89.    
  90.     cout << "The mode is: " << arr[iMaxRepeat];
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement