Search code examples
cstructurehistogrammode

finding mode from histogram


i have this function to print the histogram, I suppose to use this function calculate mode as well, I understand that to find mode you need to compare number of occurrences of each score, but I can't figured out how to implement this into the code. Is there anyway to implement this function to find mode?

this is my function

int calMode(RECORD list[], int count){
int tempMode = 0;
int i, k;
int current = 0;

while (current < count)
{
    printf("%d:", list[current].score);
    for(k=0; (i=current + k) < count ; ++k)
   {
        if(list[current].score == list[i].score)
            printf("*");
        else
            break;
    }
      if(k > tempMode)
        tempMode = k;
    printf("\n");
    current = current + k;
}
printf("%d\n", tempMode);
   return tempMode;
}

Solution

  • int calMode(RECORD list[], int count){
        int tempMode;
        int i, k;
        int current = 0;
        int max = -1;
        int update = 0;
    
        while (current < count){
            printf("%d:", list[current].score);
            for(k=0; (i=current + k) < count ; ++k){
                if(list[current].score == list[i].score)
                    printf("*");
                else
                    break;
            }
            printf("\n");
    
            if(k>max){
                max = k;
                tempMode = list[current].score;
                update  = 1;
            } else if(k == max){
                update = 0;
            }
    
            current = current + k;
        }
        if(update == 0)
            tempMode = -1;//indeterminable
        return tempMode;
    }