77.3k views
4 votes
C++

Write a program that reads in at most 100 integers that are between 1 and 100 and counts the occurrence of each number in the list. Assume the list ends when a zero is inputted.

User Ron Miles
by
3.9k points

1 Answer

5 votes

Answer:

#include <iostream>

#include <map>

using namespace std;

int main()

{

map<int, int> numbers;

cout << "Enter numbers, 0 to finish" << endl;

int number;

while (true) {

cin >> number;

if (number == 0) break;

numbers[number]++;

}

for (pair<int, int> element : numbers) {

std::cout << element.first << ": occurs " << element.second << " times" << std::endl;

}

}

Step-by-step explanation:

One trick used here is not to keep track of the numbers themselves (since that is not a requirement), but start counting their occurrances right away. An STL map< > is a more suitable construct than a vector< >.

User MinuteMed
by
4.4k points