I want to build a provram that calculates the mode,and I'm stuck.I have all the necessary knowlege to build the program,but then I'm stuck on planning the thing itself.Here is what I thought so far-
-get numbers using vectors
-sort the numbers.
-???? <- this is the bit I'm stuck on.I know I have to know which one has the most frequencies,but HOW?! Please help me.
Once the numbers are sorted, start looping through the list. When you encounter a number, keep track of it, and keep a counter. If the next number is the same, increment the counter. When you reach the end of those numbers, check how many you counted and compare to the maximum count (initialise this to zero). If it is greater, set the maximum count to the count of that number, and set the mode to that number.
int count = 0;
int max = 0;
int result;
for(int i = 0;i < numbers.size();i++) {
if (number[i] is equal to number[i + 1]) {
count++;
}
if(count is bigger than 'max') {
result = number[i];
count = 0; // reset so that the whole loop will continue.
}
}
cout << result << endl;
you shouldn't reset count to 0 when it is bigger than max, you need to keep counting until the next number is not equal to the current number. Try something like this
1 2 3 4 5 6 7 8
if (number[i] is equal to number[i + 1])
{
count++;
}
else
{
count = 0;
}
Also you need to set max to count in the event that count exceeds max.
1 2 3 4 5
if(count is bigger than 'max')
{
result = number[i];
max = count; //this is the new maximum value
}
#include<iostream>
#include<vector>
usingnamespace std;
int main() {
vector<int>mode;
int num;
int max = 0;
int result;
while(cin >> num) {
mode.push_back(num);
} // until something other than numbers are typed in,the loop continues.
int freq = 0; // this is to keep track of the continuos numbers.
sort(mode.begin(),mode.end()); // sorting the number will be easier to calculate the mode.
for (int i = 0;i < mode.size();i++) {
if(mode[i] == mode[i + 1]) {
++freq;
} // if number[i] is equal to the next number,frequency increases.
if (freq > max) {
max = freq;
result = mode[i]; // if the frequency is bigger than the max frequeny,the result should be the number[i]
}
elseif (max == 0) {
result = 0;
}
}
if(result == 0) {
cout << "there is no mode." << endl;
}
else {
cout << "the mode is: " << result << endl;
}
system("pause");
return 0;
}
okay. The program is written,and there is a new problem.
I wrote 4,4,4,4,5, and 5, and which 4 is clearly the mode,but the output is-
Using a map would allow you to keep track of the frequency of each number. You don't need to keep track of the frequency of each number, just keep track of the number with the highest frequency (and its frequency).