0
2 for each loops
Can someone please explain why 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);} //output 0 0 3 0 1 } }
3 Answers
+ 5
It works like :
First n is 1.
Hence , a[1] will be zero.
Then n will be a[1] or 0.
Hence , a[0] will be zero.
Then n will be a[2] or 3.
Hence , a[3] will be zero.
Then n will be a[3] or 0.
Hence , a[0] will be zero.
Then n will be a[5] or 1.
Hence , a[1] will be zero.
Next, for each will print each value of a array.
That is 0 0 3 0 1
+ 4
for-each loop gives you the value to use immediately BUT the loop still traverses the array one at a time.
The issue here is that the value of the array is being mutated as the loop goes.
I guess it is much clearer to just list the iterations.
a = [1,2,3,4,1], INDEX=0, a[0] = n = 1; -> a[1] = 0; -> [1,0,3,4,1]
a = [1,0,3,4,1], INDEX=1, a[1] = n = 0; -> a[0] = 0; -> [0,0,3,4,1]
a = [0,0,3,4,1], INDEX=2, a[3] = n = 3 => a[3] = 0 -> [0, 0, 3, 0, 1];
a = [0, 0, 3, 0, 1], INDEX=3, a[3] = n = 0 => a[0] = 0 -> [0, 0, 3, 0, 1];
a = [0, 0, 3, 0, 1], INDEX=4, a[1] = n = 0 => a[0] = 0 -> [0,0,3,0,1];
END-LOOP
You can see here that the index still goes from 0-4 but the value has changed.
+ 3
There are two for each loops your program.
When the first loop is executed, it sets the elements of "a" to {0, 0, 3, 0, 1}
The first value of n is 1, setting a[1] to 0 changes 2 to 0 thereby changing the array to {1, 0, 3, 4 ,1}
a is now {1, 0, 3, 4, 1}
The next value n is assigned is 0, also setting a[0] to 0 changes 1 to 0
a is now { 0, 0, 3, 4, 1}
This is the third iteration, n is now 3.
a[3] = 0 changes the array to {0, 0, 3, 0, 1}
Fourth iteration, n has the value 0
a[0] = 0
a still remains {0, 0, 3, 0, 1}
n is 1 for the last iteration
a[1] = 0
a remains {0, 0, 3, 0, 1}
The next loop is executed and it prints the value of the new array {0, 0, 3, 0, 1}
Hope this helps