Determining mode

Hi

I'm having trouble determining the mode. If the sequence is 9 3 3 3 9. The mode is found to be 9. It always tends to choose the higher value that's repeated even if it's less times. Any suggestions would be most helpful.

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
44
45
46
47
#include <iostream>
#include <vector>

using namespace std;

void read(vector<int>& myvector);
void mode(vector<int>& myvector);

int main()
{
    vector<int> myvector;
    read(myvector);
    mode(myvector);

    return 0;
}


void read(vector<int>& myvector){

    int value;
    cout << "Enter a sequence of number space delimited and q to end" << endl;
    while(cin >> value){
        myvector.push_back(value);
    }
    sort(myvector.begin(), myvector.end());
}

void mode(vector<int>& myvector){

    int counter = 1;
    int first, second;
    int num = 0;
    for (int i=1; i<myvector.size(); i++){
    first = myvector.at(i-1);
    second = myvector.at(i);

    if (second == first){
        counter ++;
        num = first;
    }

    else
        first = second;
    }
    cout << "The mode is: " << num << endl;
}
you forgot to reinitialize counter to 1 in else in the for loop in mode
Makes no difference. If I type 3 3 3 6 6 as the sequence it shows the mode as 6 still.
Makes no difference.

It makes no difference because it is not enough. You need to keep track of the current run and the longest run.
Topic archived. No new replies allowed.