(Help) Foreach loop | SoloLearn: Learn to code for FREE!


(Help) Foreach loop

int[] a={1,2,3,4,1}; for(int n:a) a[n]=0; for(int n:a) System.out.print(n+" "); Output is 0 0 3 0 1 How?? And WHY???

3/15/2018 6:43:16 AM


5 Answers

New Answer


'n' contains value which is stored in 'a'. The index position at 'n' is set equal to zero. So in the beginning, 'n' is 1 and the 2nd element (a[1]) of the array is set to 0. And so on. 'n' doesn't increase from 0 to length of array.


Try this code. It prints the array every time it loops. https://code.sololearn.com/csVpSjE071EJ/?ref=app


I don't want to make everything 0... I want to know why the values of n are 0 0 3 0 1...indexing starts from 0,1,2....so on... But here indexing is 0 0 3 0 1..why it so??


Even though you explained me, its hard to understand at the very next moment. But i got that.. You are a good geek😁😁 Thank you tejaswi...😊


if you want to make everything 0, do this: for(int i = 0; i < a.length; i++) { a[i] = 0; }