Search code examples
carraysmode

How can I program for mode if there are multiple modes?


I am able to write a program to find the mode provided there is only one mode. However, I'm not sure how to alter my code so it can function properly when there is more than one mode.

Here is what I have! Any advice on how to fix my code would be appreciated.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main ()

{
  int x, i, c[101], mode;

  printf("please enter test scores between 0 and 100\n");

  i = 0;
  mode = 0; 

  while (i<=100) 
    {
      c[i]=0;
      i=i+1;
    }

  scanf("%d", &x);

  while ((x>=0) && (x<=100)) 
    {
      c[x]=c[x]+1;

      if (c[x]>=mode)
    {mode=x;}

      scanf("%d", &x);
    }

 printf("the mode is %d\n", mode);

}

Solution

  • You'd want to:

    a) Have something that keeps track of how often each value occurred. You're already using an array of "occurrence counts" for this.

    b) Find the highest "occurrence count"

    c) Find all values that share the highest "occurrence count"

    For your code, this can mostly be done by replacing:

      if (c[x]>=mode)
          {mode=x;}
    

    ..with something more like:

      if (c[x] > highest)
          {highest = c[x];}
    

    ..and then doing something like this at the end:

        printf("the mode/s are:");
    
        for(i = 0; i <= 100; i++) {
            if(c[i] == highest) {
                printf(" %d", i);
            }
        }
    
        printf("\n");