I have to count the frequency of values in the array. I have this code:

int main()
{
int size;
int val, count;
int list[] = {3,4,3,2,4,5,7,4,7,8,4,4,3,2,4,7,8,5,4,3,3,3,4,5,5};
size = sizeof(list)/sizeof(int);

sort(list, size);
cout << "Our sorted list is: ";
print(list, size);

cout << setw(6) << "Value:" << setw(12) << "Frequnce" << endl;
getFrequency (val, list, size, count);

return 0;
}

void getFrequency (int val, int list[], int size, int &count)
{
for (int v=0; v<size; v++)
{
val = list[v] ;
int count = 0;
for (int k=0;k<size;k++)
{
if(list[k]==val)
count++ ;
}
cout << setw(3) << val << " " << setw(10) << count <<endl;
}
}

The code works, but at the end it outputs like
2 2
2 2
3 6
3 6
3 6 etc.

I can't figure out the missing part of the code so that output is only 1 of each value like
2 2
3 6
4 8 etc.

Thanks
It is because you traverse the whole array for each its element in the loop.
Your function is invalid. Also ask you the question why did you sort the arrray? Use the property of sorted arrrays to write the functiion.
Sorting of array was one of the tasks. The assignment asks first to sort the given array and then count and frequency of values. I didn't add here the definition for sort function, as it works OK.
So, what I need to do to solve the problem? Completely change the function?
Topic archived. No new replies allowed.