public class FrequencyCount {
public static void main(String[] args) {
int[] arr = {2, 3, 5, 2, 7, 3, 2, 5, 9, 9, 7, 3};
int[] freq = new int[arr.length];
int visited = -1;
for(int i=0; i<arr.length; i++){
int count = 1;
for(int j=i+1; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
freq[j] = visited;
}
}
if(freq[i] != visited){
freq[i] = count;
}
}
System.out.println("Element\tFrequency");
for(int i=0; i<freq.length; i++){
if(freq[i] != visited){
System.out.println(arr[i] + "\t" + freq[i]);
}
}
}
}
Element Frequency
2 3
3 3
5 2
7 2
9 2
arr
. We create another integer array freq
with the same length as arr
. We initialize a variable visited
with -1
, which is used to mark the elements that have already been counted.arr
and for each element, we compare it with the rest of the elements. If we find a match, we increment a variable count
. We also mark the index of the matching element in the freq
array with visited
.freq
array and print the non-visited elements along with their frequency.