+ 1
Question about array-answer
int [] n = {1, 2, 5, 1, 2, 3, 4, 2, 4, 1}; int [] occ = new int [6]; for (int i = 0; i < n.length; i ++) ++ occ [ n[i] ]; System.out.print(occ [1]); System.out.print(occ [4]); Why answer is 32?
2 Answers
+ 5
Терещенко Дмитрий Here occ is count of occurrence of number exist in array n. So here 1 occur in array 3 times, 4 occur 2 times, 2 occur 3 times, 3 occur 1 times and 5 occur 1 times.
Print like this and check
int [] n = {1, 2, 5, 1, 2, 3, 4, 2, 4, 1};
int [] occ = new int [6];
for (int i = 0; i < n.length; i ++) {
++ occ [ n[i] ];
System.out.println("occ[" + n[i] + "] = " + occ[n[i]]);
}
System.out.print(occ [1]); //1 exists 3 times in array n
System.out.print(occ [4]); //4 exists 2 times in array n
+ 2
In the for loop, the array 'n' has three 1's and two 4's so every time ++occ[n[i]]; is executed, the n[i] value works as an index for the array 'occ' and value at that index is affected.
Only the value at occ[0] will be 0, the rest will have a positive value in their respective index. Use this to check-
for(int x:occ)
System.out.println(x);