mode from array

S

Sluggoman

Cannot seem to wrap my head around this, could someone help me with the
logic? I need to pull the value which occurs most frequently from array
- am writing a mini program to get logic sorted out, but it just
doesn't get there.

int main(void)
{
int i;
int data[8];
//create static array to hold data
for (i=0;i<8;i++)
{
data = i;
}
//set static value to increase freq of 42.
data[6] = 3;
printf("data = ");

for (i=0;i<8;i++)
printf("%d ", data);


//now get frequency array
int freq[8];
for (i=0;i<8;i++)
{
freq = 0;
}


printf("\n \n freq = ");

for (i=0;i<8;i++)
printf("%d ", freq);

//now count frequency...
int freqcount = 0;//will hold frequencies
int oldfreq=0;
int nownum = 0;
int newoldfreq=0;
for(nownum=0;nownum<8;nownum++)
{
for(i=0;i<8;i++)
{
if(nownum==data)
{
freqcount ++;
if(freqcount > oldfreq)
{
nownum = newoldfreq;
}
newoldfreq=oldfreq;
}
}
}




printf("\n mode = %d \n", oldfreq);
return 0;
}

Output;
data = 0 1 2 3 4 5 3 7

freq = 0 0 0 0 0 0 0 0
mode = 0

obviously the mode should 3 - but my logic is horrible - any
suggestions on how to get this value?
 
R

Richard Heathfield

Sluggoman said:
Cannot seem to wrap my head around this, could someone help me with the
logic? I need to pull the value which occurs most frequently from array
- am writing a mini program to get logic sorted out, but it just
doesn't get there.

<code snipped>

Take a look at the following code, which does what you want. I've taken the
unusual step of commenting (almost) every line, in the hope that it helps
you clear your head a little. :)

MINVAL and MAXVAL can be tweaked to taste, within reason, if you wish.


#include <stdio.h> /* prototype for printf, and def of size_t */

#define MINVAL 0 /* the lowest allowable data value */
#define MAXVAL 42 /* the highest allowable data value */

int main(void)
{
int data[] = { 0, 1, 2, 3, 4, 5, 3, 7 }; /* initialise the data array */
int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency
* counts to 0.
*/
size_t i = 0; /* loop counter */
int mode = 0; /* for recording the modal value */

for(i = 0; i < sizeof data / sizeof data[0]; i++) /* for each datum */
{
++freq[data]; /* track the frequency */
if(freq[data] > mode) /* is this now the most common item? */
{
mode = data; /* yes, so log it */
}
}
printf("The modal value is %d which occurs %d time%s.\n",
mode,
freq[mode],
freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,938
Members
47,473
Latest member
pioneertraining

Latest Threads

Top