java

Java – Count the Number of Occurrences in an Array

In this tutorial, we are going to see how to count the number of occurrences in an array in Java.
 

Program to Count the Number of Occurrences in an Array
public class Main {
    public static void main(String[] args) {
        int [] arr = new int [] {1, 1, 7, 3, 2, 2, 2, 4, 1};
        int [] count = new int[100];
        /* i: counter, tmp: stock tmporarily the value
        at a certain index of the array arr[] */
        int i,tmp = 0;

        /* tmp will act as an index value for the count array and
        will keep track of the number of occurrences of each number */
        for(i = 0; i < arr.length; i++){
                tmp = arr[i];
                count[tmp]++;
        }

        for(i=1; i < count.length; i++){
            if(count[i] > 0 && count[i] == 1){
                System.out.printf("%d occurs %d times\n",i, count[i]);
             }
            else if(count[i] >= 2){
                System.out.printf("%d occurs %d times\n",i, count[i]);
            }

         }
    }
}

Output:

1 occurs 3 times
2 occurs 3 times
3 occurs 1 times
4 occurs 1 times
7 occurs 1 times
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *