Well I have one solution for you and while it is one of many ways to attack this, it isn't by all means the only way. You could have created a function to also check if the value has already been found.
Here I go with the approach of basically "crossing off" values that have been counted by setting them to zero. Then when it comes to printing I just skip over the crossed off values.
This would leave some null values in your listNum2 and listcount arrays, since you are not appearing to do much with them I figured it wasn't a big deal.
Here is the solution...
cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int num, bil;
int array[20] = {175, 167, 160, 164, 183, 187, 188, 179, 176, 175, 169, 175, 176, 178, 165, 160, 173, 165, 187, 178};
int listcount[20], listNum2[20];
int elements = sizeof(array) / sizeof(array[0]);
sort(array, array + elements);
// Calculate our sum first before we go modifying values
double Sum = 0;
for (int i = 0; i < 20; i++)
{
Sum = Sum + array[i];
}
// Get our median value while we are at it
double median = (array[9]+array[10])/2;
// Loop through the array values
for ( int c = 0; c < 20; c++ )
{
bil = 0;
num = array[c];
// If the number is greater than 0, it means it hasn't been counted yet
if (num > 0) {
for ( int x = 0; x < 20; x++ ) {
if ( num == array[x] ) {
bil++;
// Value counted, so set it to zero so it won't be counted again
array[x] = 0;
}
}
// Save the number and its count
listNum2[c] = num;
listcount[c] = bil;
}
}
cout << "Height \t number of Pupils \n";
for ( int y = 0; y < 20;y++ ) {
// We don't want to list values that are zero (repeats)
if (listNum2[y] > 0) {
cout << listNum2[y] << " " << listcount[y] <<endl;
}
}
// Display our average and median
cout<<endl<<"The average Height = "<<Sum/20<<endl;
cout << "Median height = " << median << endl;
return 0;
}
As you can see when we go to count each occurrence, we simply cross it off with a zero. Then whenever the loop comes across a zero, it skips counting it.
At least it will give you an idea what is happening for you and you can take a different approach if necessary. Enjoy!
"At DIC we be crossing off number code ninjas, and if you don't watch out we will cross you off too!"