Thread: finding mode of an array

  1. #1
    Registered User
    Join Date
    Apr 2004

    finding mode of an array

    hi can someone please explain how to find the mode of an array. i have a program that takes input until EOF. then the program takes the inputs, finds the mean, median, mode, and standard deviation. i looked at past threads but i'm still confused on how to do it.
    can someone explain how this works. you don't have to give me the code, as long as you can please explain how everything works. by the way, this program is due at 10 PM so i'm in desperate need. thanks

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Well, you may be screwed by now, but the mode is simply the item in a list that occurs most frequently. For small ranges, I usually recommend a frequency table. Here's an example:
    #include <stdio.h>
    #include <stdlib.h>
    int get_mode(int a[], int size, int max);
      int a[10];
      int i;
      for (i = 0; i < 10; i++) {
        a[i] = rand() % 10;
      printf("Mode: %d\n", get_mode(a, 10, 10));
      return 0;
      int a[],  /* List of numbers */
      int size, /* Size of list */
      int max   /* Upper range limit */
      int *freq;
      int  i;
      int  mode;
      /* Allocate and zero fill a table */
      freq = calloc(max, sizeof *freq);
      /* Increment the appropriate element for each occurance of a[i] */
      for (i = 0; i < 10; i++) {
        ++freq[ a[i] ];
      /* Find the first largest element */
      mode = 0;
      for (i = 0; i < max; i++) {
        if (freq[i] > mode) {
          mode = i;
      return mode;
    The idea is that the frequency table has an element for every possible value in a range. The list will only have values within that range, so if you use the item in the list as an index for the table, you can keep a high performance count of occurances. But don't forget that a list can have more than one mode. I'll leave the solution for that particular problem up to you.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Finding largest number in array
    By el_chupacabra in forum C Programming
    Replies: 2
    Last Post: 01-22-2009, 02:31 PM
  2. Finding array dimensions
    By deviousdexter in forum C# Programming
    Replies: 3
    Last Post: 11-12-2008, 10:34 AM
  3. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  4. Finding a hyphen in an array.
    By omnificient in forum C Programming
    Replies: 7
    Last Post: 06-17-2008, 02:31 AM
  5. Finding largest element in array
    By Chaplin27 in forum C++ Programming
    Replies: 2
    Last Post: 04-12-2005, 09:18 PM