Print how many times has a number repeated in following array
int x[] ={1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
Your output should look like
1- 3 times
2 - 2 times
...
The logic should work even if we change the array.
-- The solution provided for above question. The code is not printing the frequecy of the number 311. It is just printing till the element 43.
Can you please let me know how to print the frequency gets populated even for the element 311
Instructor
Ashish Thakur Replied on 13/01/2019
public class PrintArrayRepitition {
public static void main(String[] args) {
int x[] ={1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,43,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
//int x[] ={1,1,3,2,3,1,5};
for(int i=0;i<x.length;i++) {
for(int j=i+1;j<x.length;j++) {
if(x[i] > x[j]) {
int temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
}
for(int i=0;i<x.length;i++) {
System.out.println(x[i]);
}
boolean exit=false;
for(int i=0;i<x.length;i++) {
int count=0;
int j=i;
for(j=i;j<x.length;j++) {
//System.out.println(x[i]+"--"+x[j]);
if(x[i] == x[j]) {
count++;
}else {
break;
}
}
System.out.println(x[i]+"is repeated "+ count+" times");
i=j-1;
if(exit)
break;
}
}
}