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

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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.