0

can someone explain it to me?

public class Main { 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); } } }

6th Nov 2020, 12:30 PM
Samer Mazraani
Samer Mazraani - avatar
3 Respostas
6th Nov 2020, 12:43 PM
Avinesh
Avinesh - avatar
+ 1
It sets certain elements in a to 0, but not all. First iteration n=a[0]=1 sets a[1] to 0 Second iteration n=a[1]=0 (because a[1] was set to 0 in first iteration) sets a[0] to 0 And so on The trick to understand is that updates are immediate
6th Nov 2020, 12:48 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Thanks for this explanation i was thinking why it's not working as index a[0]=1 a[1]=2 a[2]=3 ..
6th Nov 2020, 12:50 PM
Samer Mazraani
Samer Mazraani - avatar