Search code examples
carraysmode

Coding for multiple modes in C?


My assignment is to find all possible modes for a set of numbers (0 to 100).

We were told to do so using arrays and also to count the frequency that each number occurs.

I've coded for the mode, however, my program does not work is there are multiple modes (example: 1, 2, 7, 7, 9, 10, 7, 2, 2. In this stance, 2 and 7 are both the mode and my program needs to print both of them, but mine doesn't).

I think I might have to make another array set, but I'm not sure? Any advice would be appreciated.

Here is what I have:

#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) { //setting all values to 0 
        c[i] = 0;
        i = i + 1;
    }

    scanf("%d", &x); // scanning in the test scores 

    while ((x >= 0) && (x <= 100)) { // counting how often each score appears 
        c[x] = c[x] + 1;

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

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

    printf("THE MODE(S) ARE %d\n", mode);

    i = 0;

    while (i <= 100) { //printing all values so long as they've occurred at least once 
        if (c[i] > 0) {
            printf("%d occurs %d times\n", i, c[i]);
        }
        i = i + 1;
    }
}

Solution

  • You have to count the highest frequency of any number and if that frequency equals the frequency of any other number then that number will also be mode. So the changes that you need to do are:

    #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) //setting all values to 0 
        {
          c[i] = 0;
          ++i;
        }
      scanf("%d", &x); // scanning in the test scores 
      while ((x >= 0) && (x <= 100)) // counting how often each score appears 
        {
          c[x] = c[x] + 1;
          if (c[x] >= mode)
          {mode = c[x];}
          scanf("%d", &x);
        }
      for(i=0;i<=100;i++){//printing all values having highest frequency
        if (c[i]==mode)
        {
            printf("THE MODE(S) ARE %d\n", i);
       }
       i = 0;
       while (i<=100) //printing all values so long as they've occurred at least once 
       {
       if (c[i] > 0)
         {
           printf("%d occurs %d times\n", i, c[i]);
          }
       ++i;
       }
    }