0
Help with understanding this code (Java)
I can't figure out why the output is 0 0 3 0 1 public class Program { public static void main(String[] args) { int[] a = {1,2,3,4,1}; for(int n : a) a[n] = 0; for(int n : a) System.out.println(n); } }
2 Réponses
+ 3
In line a[n]=0 you are using array values as index.
Step 1:
n=1 (first value in array)
a[1]=0
array: [1, 0, 3, 4, 1]
Step 2:
n=0 (2 was replaced by 0 in step 1)
a[0]=0
array:[0, 0, 3, 4, 1]
Step 3:
n=3
a[3]=0
array:[0, 0, 3, 0, 1]
And so on
0
Aleksandrs thanks now I understand