C Program to Find Mode of an Array

This C program finds mode in an array.

Here is the source code of the C program to display mode of an array. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C progarm to find mode in an array
  3.  */
  4. #include <stdio.h>
  5.  
  6. int main()
  7. {
  8.     int i, j, a[20] = {0}, sum = 0, n, t, b[20] = {0}, k = 0, c = 1, max = 0, mode;
  9.     float x = 0.0, y = 0.0;
  10.     printf("\nEnter the limit\n");
  11.     scanf("%d", &n);
  12.     printf("Enter the set of numbers\n");
  13.     for (i = 0; i < n; i++)
  14.     {
  15.         scanf("%d", &a[i]);
  16.     }
  17.     for (i = 0; i < n - 1; i++)
  18.     {
  19.         mode = 0;
  20.         for (j = i + 1; j < n; j++)
  21.         {
  22.             if (a[i] == a[j]) {
  23.                 mode++;
  24.             }
  25.         }
  26.         if ((mode > max) && (mode != 0)) {
  27.             k = 0;
  28.             max = mode;
  29.             b[k] = a[i];
  30.             k++;
  31.         }
  32.         else if (mode == max) {
  33.             b[k] = a[i];
  34.             k++;
  35.         }
  36.     }
  37.     for (i = 0; i < n; i++)
  38.     {
  39.         if (a[i] == b[i]) 
  40.             c++;
  41.         }
  42.         if (c == n)
  43.             printf("\nThere is no mode");
  44.         else
  45.         {
  46.             printf("\nMode\t= ");
  47.             for (i = 0; i < k; i++)
  48.                 printf("%d ",b[i]);
  49.         }
  50.         printf("\n");
  51.         return 0;
  52.     }

$ gcc mode.c 
$ a.out
 
Enter the limit
10
Enter the set of numbers
1 2 2 3 4 5 5 6 7 8  
 
Mode    = 2 5

Sanfoundry Global Education & Learning Series – 1000 C Algorithms.

advertisement
advertisement
If you wish to look at all C Algorithms and Solutions, go to C Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.