Hi,
I am doing program to read 5 numbers from user and outup the number that is used the most of the time.
For example user input is 1,2,3,4,1 the output would be 1 or 6,5,5,5,6 output is 6.
But as I tried to make it work I have more and more problems.
Here is a much more C++ way of doing it. It makes use of existing C++ data structures.
A map is used to keep track of the actual values entered, and how many times they're entered.
Then, an existing standard algorithm, max_element, is used to iterate over that map, and find the key-value pair with the greatest value. The greatest value is determined according to the lambda function pass to the max_element function. The max_element function returns an iterator to the winning pair, and that iterator is used to get the winning key (->first)
Note also that the main function is of form int main(). void main() is wrong. Just plain wrong.
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
int main()
{
std::map<int, int> values;
int inputCount = 5; // Change this value to take in as many as you like
while (inputCount--)
{
int input;
std::cin >> input;
values[input]++; // Each time user enters a number, increment the count of that number
}
std::cout << "Most frequent: " << std::max_element(values.begin(), // From here...
values.end(), // to here...
[](const std::pair<int, int>& p1, const std::pair<int, int>& p2)
{return p1.second < p2.second; })->first;
}
Okey dokey. That's what the code does. What do you want to happen if there is more than one most common number? What is the output in the following cases:
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
int main()
{
std::map<int, int> values;
int inputCount = 5; // Change this value to take in as many as you like
while (inputCount--)
{
int input;
std::cin >> input;
values[input]++; // Each time user enters a number, increment the count of that number
}
int top = std::max_element(values.begin(), // From here...
values.end(), // to here...
[](const std::pair<int, int>& p1, const std::pair<int, int>& p2)
{return p1.second < p2.second; })->second;
for (constauto& pairing : values)
{
if (pairing.second == top) std::cout << pairing.first << " ";
}
}