How does the For cycle work in arrays?

-2

I'm practicing exercises with arrays, I found this code:

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[1]);
System.out.println(occ[4]);

the result of running the code is 3 and 2 but I do not understand this part that works   ++occ[n[i]];

    
asked by jairo rivera 23.05.2018 в 09:17
source

1 answer

10

Let's analyze the code a bit:

int[] n = {1, 2, 5, 1, 2, 3, 4, 2, 4, 1};

declares and initializes an array of 10 positions that stores 10 integers ( int ) defined. Note that all numbers are between 0 and 6

int[] occ = new int[6];

declares and initializes an array of 6 positions, but the values are not defined. Since an int can not be null , all positions take the default value: 0 (zero)

for (int i = 0; i < n.length; i++) { //bucle de 10 iteraciones
    ++occ[n[i]];
}

The complex part of the loop I am going to rewrite it like this:

int indice= n[i]; //tomamos el valor de la posición i del array n
++(occ[indice]); //equivalente a occ[indice] = occ[indice] +1;

Therefore, n is an array that stores the positions that will be incremented by 1 in the occ array.

For example, in the array n appears 1 three times, so position 1 of the array occ will be incremented 3 times. The 4 appears 2 times, so that position will be worth 2 after the loop.

System.out.println(occ[1]); // 3
System.out.println(occ[4]); // 2

You can see the operation step by step here

    
answered by 23.05.2018 / 10:33
source