+ 1

(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???

15th Mar 2018, 6:43 AM
Harish
5 Answers
+ 4
'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.
15th Mar 2018, 7:06 AM
Tejaswi Hegde
Tejaswi Hegde - avatar
+ 1
Try this code. It prints the array every time it loops. https://code.sololearn.com/csVpSjE071EJ/?ref=app
15th Mar 2018, 6:52 AM
Tejaswi Hegde
Tejaswi Hegde - avatar
+ 1
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??
15th Mar 2018, 7:01 AM
Harish
+ 1
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...šŸ˜Š
15th Mar 2018, 7:28 AM
Harish
0
if you want to make everything 0, do this: for(int i = 0; i < a.length; i++) { a[i] = 0; }
15th Mar 2018, 6:55 AM
Tejaswi Hegde
Tejaswi Hegde - avatar