count frequencies of all elements in array


import java.io. * ;
import java.util. * ;
class frequencies {
	public static void main(String args[]) {
		int count = 0;
		Scanner sc = new Scanner(System. in );
		int n[] = new int[20];
		int ans[][] = new int[20][2];
		int z = 0;
		System.out.println(" Enter Numbers : ");
		while (true) {
			n[z] = sc.nextInt();
			if (n[z] == -1) {
				break;
			}
			count++;
			z++;
		}
		int n1[] = new int[count];
		for (int i = 0; i < count; i++) {
			n1[i] = n[i];
		}
		for (int i = 0; i < n1.length; i++) {
			if (n1[i] == -1) {
				break;
			}
			ans[i][0] = n1[i];
			count = 0;
			for (int j = 0; j < n1.length; j++) {
				if (ans[i][0] == n1[j]) {
					count++;
				}
			}
			ans[i][1] = count;
		}
		int temp = 0;
		for (int i = 0; i < n1.length; i++) {
			for (int j = 1; j < n1.length - 1; j++) {
				if ((ans[j - 1][1]) < (ans[j][1])) {
					temp = ans[j - 1][1];
					ans[j - 1][1] = ans[j][1];
					ans[j][1] = temp;
					temp = ans[j - 1][0];
					ans[j - 1][0] = ans[j][0];
					ans[j][0] = temp;
				}
			}
		}
		int print = 0;
		System.out.println(" NUMBER : " + ans[0][0] + " Frequency : " + ans[0][1]);
		for (int i = 1; i < n1.length; i++) {
			if (n1[i] == -1) {
				break;
			}
			for (int j = 0; j < i; j++) {
				if (ans[i][0] == ans[j][0]) {
					print++;
				}
			}
			if (print == 0) System.out.println(" NUMBER : " + ans[i][0] + " Frequency : " + ans[i][1]);
			print = 0;
		}
	}
}

Output:
 Enter Numbers : 1   5   4   2   1   2   5   1   1   2   4   5   5  -1
 NUMBER : 1     Frequency : 4
 NUMBER : 5     Frequency : 4
 NUMBER : 2     Frequency : 3
 NUMBER : 4     Frequency : 2

You may also like...

Leave a Reply

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