0

Can anyone explain why - 0 0 3 0 1- is the output?

Int[] a = {1,2,3,4,1}; for (int n: a) a[n] = 0; for (int n: a) System.out.println(n)

9th May 2019, 3:12 PM
Mimi
Mimi - avatar
4 Answers
+ 20
Mimi Its enhanced for loop, sololearn have a lesson on it : https://www.sololearn.com/learn/Java/2209/
9th May 2019, 6:27 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 7
You can print the current array in the loop to see it yourself. n starts with the first value in the array (1) and moves through it: n=1 a[1] = 0 => a = {1,0,3,4,1} So the next value is 0 (second entry) n=0 a[0] = 0 => a = {0,0,3,4,1} next value is 3 (third entry) n=3 a[3] = 0 => a = {0,0,3,0,1} next value is 0 (fourth entry) n=0 a[0] = 0 => a = {0,0,3,0,1} no change, the first entry has already been set to 0 Next (and last) n is 1, end of array. n=1 a[1] = 0 => a = {0,0,3,0,1} again no change, since a[1] was 0 before too So final result a = {0,0,3,0,1}
9th May 2019, 3:31 PM
Matthias
Matthias - avatar
+ 2
Thank you so much! 😅 I wasn't familiar with the n:a sentence or whatever it's called, I thought that n is getting the index, not the value. So I thought it should output 0 0 0 0 0...
9th May 2019, 4:02 PM
Mimi
Mimi - avatar
+ 1
Gaurav Agrawal Thanks a lot!
10th May 2019, 10:58 AM
Mimi
Mimi - avatar