+ 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???
5 Antworten
+ 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.
+ 1
Try this code. It prints the array every time it loops.
https://code.sololearn.com/csVpSjE071EJ/?ref=app
+ 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??
+ 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...😊
0
if you want to make everything 0, do this:
for(int i = 0; i < a.length; i++) {
a[i] = 0;
}