I want to write a program that reads at most 100 integers between 1 and 100 and counts the occurrence of each number.(input ends with 0)
I don't know why the codes fail to run. I'm using visual c++ 2010 express.
#include <iostream>
usingnamespace std;
int main()
{
int input;
int count=0;
int num[100];
cout << "Enter the integers between 1 and 100: ";
for(int i=0; i<100; i++)
{
cin >> input;
if(input==0||input<1||input>100)
{break;}
else
{num[i]=input;
count++;}
}
for(int i=0; i<count; i++)
{
int currentmin=num[i];
int currentminindex=i;
for(int j=i; j<count; j++)
{if(currentmin>num[j])
currentmin=num[j];
currentminindex=j;}
if(currentminindex!=i)
num[currentminindex]=num[i];
num[i]=currentmin;
}
int count2[100]={0};
for(int i=0; i<count; i++)
{
count2[num[i]]++;
}
for(int i=0; i<count; i++)
{
cout << num[i] << " occurs " << count2[num[i]];
if(count2[num[i]]==1)
{cout << " time" << endl;}
else
{cout << " times" << endl;}
}
return 0;
}
I entered 5 5 5 44 33 12 1, and the result is :
Enter the integers between 1 and 100: 5
5
5
44
33
12
1
0
1 occurs 1 time
5 occurs 3 times
5 occurs 3 times
5 occurs 3 times
12 occurs 3 times
12 occurs 3 times
12 occurs 3 times
33 and 44 are missing, but 12 becomes 3 times.
Also, I would like to know how to make the result like 5 occurs 3 times, but not repeating the
statement 3 times.
Store the progressive results in an array as you go through the list of numbers. Increment each element as appropriate and then loop through the array once all the input numbers have been accounted for. :)
@OP - are you allowed to use STL? A better solution would use something like std::multimap and check the frequencies directly - it's exactly what it's designed for. Given this looks like a basic C++ homework question, using STL might not be an option, and no-ones going to write your code for you, so you may be stuck trying to fix the original code which doesn't look very well designed (at first glance, it looks too 'hard-coded' and not generic enough), in which case kemort's answer would work.