Occurrence of a particular element in an Array – Java

Today we will see how to count the number of occurrences of a particular element in an Array in Java.

Example:

If the array is :  10   15   17   19   19    15    10    10

Number: 10

Occurrence: 2

Since 10 comes 2 times in the array, therefore, the answer is 2.

Now we will write a Java program for the same:

Count the ccurrence of a particular element in an Array in Java

import java.util.*;
public class test
{ 
    public static void main(String args[]) 
    { 
        int arr[]=new int[10];
        int num;
        int occ=0;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter array elements");
        for(int i=0;i<=9;i++)
        {
        	arr[i]=sc.nextInt();
        }
        System.out.println("Enter the number whose occurence is to be found ");
        num=sc.nextInt();
        for(int i=0;i<=9;i++)
        {
        	if(arr[i]==num)
        	{
        		occ++;
        	}
        }
        System.out.println("Number occurs "+occ+" times");
        
        
        
    } 
}

In the above program, we are just comparing the number with each element in the array. If the number is the same then we increment the counter.

The output will be as follows:

Enter array elements
10
20
30
10
40
50
40
20
13
20
Enter the number whose occurence is to be found 
20
Number occurs 3 times
Enter array elements
10
10
10
20
10
10
34
23
40
49
Enter the number whose occurence is to be found 
10
Number occurs 5 times

Also read:

Leave a Reply

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