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)
4 Réponses
+ 20
Mimi
Its enhanced for loop, sololearn have a lesson on it :
https://www.sololearn.com/learn/Java/2209/
+ 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}
+ 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...
+ 1
Gaurav Agrawal
Thanks a lot!