Mode Question


For my comp sci class i need to fix code i made for a program that calculates the mode of a specified amount of numbers and spits it out at the end.I have my program working to find the mode of numbers that occur more than the others such as and input 3 3 3 1 will return 3 but if I put in say 2 2 4 4 the program will only spit out 4 instead of 2,4. Help?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
int main () {
    int amount;
    int temp;
    int num;
    vector <int> vectorToSort;
    cout << "How many integers would you like to enter?" << endl;
    cin >> amount;
cout << "Please enter as many numbers from 1-20 as you would like." << endl;

for (int i = 0; i < amount; i++) {
    cin >> num;
    vectorToSort.push_back (num);
    cout << endl;
}

for (int i =0; i < vectorToSort.size(); i++) {
 for (int j=0; j < vectorToSort.size()-1-i; j++) {
    if (vectorToSort[j] > vectorToSort[j+1]) {
        temp = vectorToSort [j];
        vectorToSort [j] = vectorToSort[j+1];
        vectorToSort [j+1] = temp;
    }
 }
}
int counter = 1;
int max = 0;
int mode = vectorToSort [0];
 for (int pass = 0; pass < vectorToSort.size() - 1; pass++)
        {
           if ( vectorToSort [pass] == vectorToSort [pass+1] )
           {
              counter++;
              if ( counter > max )
              {
                  max = counter;
                  mode = vectorToSort[pass];
              }
           } else
              counter = 1;
        }
    cout << "The mode is: " << mode << endl;
}
Last edited on
Topic archived. No new replies allowed.