LearnFrenzy
Sign in Take a free test

Arrays in Java · Java Array Programs · Question 9

Count occurrences and find the most frequent element in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Read numbers in the range 0–100, count how often each appears using an int array, and print every value that appears more than once plus the most frequent value.

Solution
Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] count = new int[101];
        while (in.hasNextInt()) count[in.nextInt()]++;
        int mode = 0;
        StringBuilder repeated = new StringBuilder();
        for (int v = 0; v <= 100; v++) {
            if (count[v] > 1) repeated.append(v).append('x').append(count[v]).append(' ');
            if (count[v] > count[mode]) mode = v;
        }
        System.out.println("repeated: " + repeated.toString().trim());
        System.out.println("most frequent: " + mode + " (" + count[mode] + " times)");
    }
}

Output Verified by compiling and running

repeated: 64x2 72x4 85x2
most frequent: 72 (4 times)

For a small known range, the value itself is the index into the counting array – O(n) with no sorting or maps.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links