Java Program to Find the Mode in a Data Set

This is a java program to find the mode of a set. The mode of a set is defined as the highest occurring element in the set. We count the occurrence of each of the element and print the element whose count is highest.

Here is the source code of the Java Program to Find the Mode in a Data Set. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a java program to find the mode for a given sequence of numbers
  2. import java.util.Random;
  3.  
  4. public class Mode 
  5. {
  6.     static int N = 20;
  7.     static int[] sequence = new int[N];
  8.  
  9.     public static int mode() 
  10.     {
  11.         int maxValue = 0, maxCount = 0;
  12.  
  13.         for (int i = 0; i < sequence.length; ++i) 
  14.         {
  15.             int count = 0;
  16.             for (int j = 0; j < sequence.length; ++j) 
  17.             {
  18.                 if (sequence[j] == sequence[i])
  19.                     ++count;
  20.             }
  21.             if (count > maxCount) 
  22.             {
  23.                 maxCount = count;
  24.                 maxValue = sequence[i];
  25.             }
  26.         }
  27.  
  28.         return maxValue;
  29.     }
  30.  
  31.     public static void main(String args[]) 
  32.     {
  33.         Random random = new Random();
  34.  
  35.         for (int i = 0; i < N; i++)
  36.             sequence[i] = Math.abs(random.nextInt(100));
  37.  
  38.         System.out.println("The set of numbers are: ");
  39.         for (int i = 0; i < N; i++)
  40.             System.out.print(sequence[i] + " ");
  41.  
  42.         System.out.println("\nThe mode of the set is: " + mode());
  43.     }
  44. }

Output:

$ javac Mode.java
$ java Mode
 
The set of numbers are: 
85 3 80 56 37 47 13 11 94 38 6 12 10 31 52 67 81 98 43 37 
The mode of the set is: 37

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

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.