This is the Java Program to Print Elements Which Occurs Even Number of Times.
Given an array of elements, print the elements whose frequency is even.
Example:
array = {5, 5, 2, 2, 2, 4, 4, 1, 7, 1}
Output = 5 4 1
Create a separate array of boolean values of the same length as that of the original array, and initialize it to false. Iterate through the array to find the frequency of the frequency of each element and also mark the index which is already visited as true, to avoid printing the same element twice. Print the elements with even frequency.
Here is the source code of the Java Program to Print Elements Which Occurs Even Number of Times. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Print Elements Which Occurs Even Number of Times
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EvenFrequencyElements {
// Function to print even frequency elements
static void printEvenFrequencyElements(int[] array){
boolean[] check = new boolean[array.length];
int i,j,count;
for(i=0; i<array.length; i++){
if(!check[i]){
count=1;
for(j=i+1;j<array.length;j++){
if(array[j] == array[i]){
count++;
check[j]=true;
}
}
if(count%2==0){
System.out.println(array[i]);
}
}
}
}
// Main function to read input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
}
System.out.println("The even frequency elements are");
printEvenFrequencyElements(array);
}
}
1. In function printEvenFrequencyElements(), a boolean array check is created to store the status if the array element is already visited or not.
2. The loop for(i=0; i<array.length; i++) iterates through the array.
3. The condition if(!check[i]) checks if the element is already visited.
4. If the element is not visited already, then the count is initialized to 1 and a nested loop for(j=i+1;j<array.length;j++).
5. The elements with even frequency are printed.
Time Complexity: O(n2) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the size of the array 10 Enter array elements 5 5 2 2 2 4 4 1 7 1 The even frequency elements are 5 4 1 Case 2 (Simple Test Case - another example): Enter the size of the array 9 Enter array elements 1 2 1 2 3 3 3 8 9 The even frequency elements are 1 2
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Java Books
- Practice Programming MCQs
- Apply for Java Internship
- Apply for Computer Science Internship
- Practice Information Technology MCQs