Counting Value instances in an array

I need help counting the number of times an integer comes up in an array of numbers.
PLEASE Help!!

this is what i have:

include "DarkGDK.h"

void DarkGDK(void)
{

char dataline[40];
char *p = dataline;

float data [1000];
int N = 1000;

int filenum = 1;



dbOpenToRead(filenum,"randomdata.txt");

if(dbFileOpen(filenum)){
dbPrint("File open!");


}
else{
dbPrint("Could not open file");
dbWaitKey();
return;
}



int histogram[50];
float sum = 0.0;

int a;
for (int i=0; i<N; i++){
p = dbReadString(filenum);
data[i] = atof(p);
sum = sum + data[i];


}
dbPrint(sum);

// this is whats not working, the histogram array should
// be the one counting the number of instances
for(int i=0; i<50; i++){

a = static_cast<int>(data[i]);

histogram[a]++;
}


char outputstring[40];
sprintf(outputstring,"%d", histogram[25]);
dbPrint(outputstring);



dbWaitKey();
return;

}
The histogram counting code needs to run through the whole data array, not just the first 50 elements.

You should also be checking that 'a' is within the bounds 0 <= a < 50, otherwise, if you get a value from the db that's greater then 49 (or less that 0), your histogram[a]++ statement will overrun the array bounds and cause "bad things" to happen.

There's also no need to do the two operations separately - you can read the data and collate the histogram in the first for-loop; this saves you a lot of time running through the array twice.

Jim
Topic archived. No new replies allowed.