Mode Program In C


Advertisements

In statistics maths, a mode is a value that occurs the highest numbers of time.

For Example − assume a set of values 3, 5, 2, 7, 3. The mode of this value set is 3 as it appears more than any other number.

Algorithm

We can derive an algorithm to find mode, as given below −

START
   Step 1 → Take an integer set A of n values
   Step 2 → Count the occurence of each integer value in A
   Step 3 → Display the value with highest occurence
STOP

Pseudocode

We can now derive pseudocode using the above algorithm, as follows −

procedure mode()
   
   Array A
   FOR EACH value i in A DO
      Set Count to 0
      FOR j FROM 0 to i DO
         IF A[i] = A[j]
            Increment Count
         END IF
      END FOR
      
      IF Count > MaxCount
         MaxCount =  Count
         Value    =  A[i]
      END IF
   END FOR
   DISPLAY Value as Mode
   
end procedure

Implementation

Implementation of this algorithm is given below −

#include <stdio.h>

int mode(int a[],int n) {
   int maxValue = 0, maxCount = 0, i, j;

   for (i = 0; i < n; ++i) {
      int count = 0;
      
      for (j = 0; j < n; ++j) {
         if (a[j] == a[i])
         ++count;
      }
      
      if (count > maxCount) {
         maxCount = count;
         maxValue = a[i];
      }
   }

   return maxValue;
}

int main() {
   int n = 5;
   int a[] = {0,6,7,2,7};

   printf("Mode = %d ", mode(a,n));

   return 0;
}

Output

Output of the program should be −

Mode = 7
mathematical_programs_in_c.htm
Advertisements