Help with mode Project

I have a project where I have to determine the mode from an array of numbers. I got that to work by sorting the array and determining which number came up the most. We also have to display "Your values have no mode" if true. For example if 1 2 3 4 5 were entered, "Your values have no mode" should be displayed. I'm guessing an "if statement" will be used, but I'm not sure what it should say or where it should be located in my program. Any help would be appreciated.



#include <iostream>
using namespace std;
const int MaxSize = 100;

int main()
{
int positive[MaxSize], value, count = 0;
cout<<"Enter values ending in -1: ";
cin>>value;


while(value != -1 && count < MaxSize)
{
positive[count] = value;
count++;
cin>>value;
}

int insert;

for(int i = 0; i <count; i++)
cout<<positive[i]<<endl;

for(int next = 1; next < count; next++)
{
insert = positive[next];

int moveItem = next;

while((moveItem > 0) && (positive[moveItem -1] > insert))
{
positive[moveItem] = positive[moveItem -1];
moveItem--;
}

positive[moveItem] = insert;
}
cout<<endl;
for(int i =0; i < count; i++)
{
cout<<positive[i]<<endl;
}

int numCount[MaxSize] = {0};
int largestCount, mode;

for(int g = 0; g < count; g++)
{
for(int h = 1; h<count; h++)
{
if(positive[g] == positive[h])
numCount[g]++;
}
}

mode = positive[0];

largestCount = numCount[0];

for(int last = 0; last < count; last++)
{

if(numCount[last] > largestCount)
{
largestCount = numCount[last];
mode = positive[last];
}

}

if(largestCount == 0)
cout<<"Your values have no mode.";
else
cout<<"The mode of your values is "<<mode<<".";

return 0;
}

Last edited on
Hi

there is no need to sort the data first, all you need to count how many a number is repeated in the array, you should use two loops, one inside another so that you could count the mode for each element and compare it with the mode of other elements, and finally print out the largest mode.

some thing like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
void mode(int* a, int size){

	int m = 0 ;
	int md = 0 ;
	int index = -1;
	for(int i = 0 ; i < size ; i++){
		m = 0 ;
		for(int j = 0 ; j < size ; j++  ){
			if(a[i] == a[j]){
				m++;
			}
		}
		if( md < m ){
			md = m;
			index = i;
		}
	}
	if(md > 1){
		cout<<"The mode of your values is : "<< md << endl;
		if(index != -1){
			cout<<"the most reapeated element is : "<<a[index]<<endl;
		}
	}
	else{
		cout<<"Your values have no mode"<<endl;

	}
}


main(){

        int a[]={2,5,6,5,8,5,2,5,2,7};
       mode(a,10);

     // other things 
}
Topic archived. No new replies allowed.