0

# Can someone explain this code to me? Counting occurrence of a number. Works fine but need explanation

Scanner input = new Scanner(System.in); int[] number = new int[100]; System.out.print("Enter the integers between 1 and 100: "); for (int i = 0; i < number.length; i++) { int a = input.nextInt(); number[a] += a; if (a == 0) break; } for (int i = 1; i < number.length; i++) { if (number[i] != 0) { if (number[i] / i > 1) System.out.println(i + " occurs " + number[i] / i + " times"); else System.out.println(i + " occurs " + number[i] / i + " time"); } } } }

1 Answer

0

number[i] gets incremented by i every time we see the actual number i in the input.
So in the end, in order to count the actual number of occurrences for i, we need number[i]/i .
I would optimize it by simply incrementing by 1 every time we see the number, and printing number[i] directly :)