This is a Java Program to Count the Number of Occurrence of an Element in an Array.
Enter size of array and then enter all the elements of that array. Now enter the element of which you want to count occurrences. With the help of for loop now we can easily calculate number of occurrences of the given element.
Here is the source code of the Java Program to Count the Number of Occurrence of an Element in an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Count_Occurrence
{
public static void main(String[] args)
{
int n, x, count = 0, i = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the element of which you want to count number of occurrences:");
x = s.nextInt();
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
count++;
}
}
System.out.println("Number of Occurrence of the Element:"+count);
}
}
Output:
$ javac Count_Occurrence.java $ java Count_Occurrence Enter no. of elements you want in array:5 Enter all the elements: 2 3 3 4 3 Enter the element of which you want to count number of occurrences:3 Number of Occurrence of the Element:3
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Apply for Java Internship
- Apply for Computer Science Internship
- Check Java Books
- Check Programming Books
- Practice Programming MCQs