+ 2
Help understand the iteration
int[] a = {1, 2, 3, 4, 1}; for (int n: a) a[n] = 0; for (int n: a) System.out.println(n);
10 odpowiedzi
+ 3
This for takes an element n from the array a one by one.
First loop is
a[1] =0
a[0] =0
a[3] =0
a[0] =0
a[1] =0
+ 3
Хммм интересно
+ 3
А, понятно, у нас же значения уже поменялись некоторые на ноль, поэтому там такая штука
+ 3
Vasiliy да, я как обычно не заметила
Не люблю такие тесты на внимательность))
+ 1
Maria Vasilyova, я тоже так подумал ☺️, но нет, правильный ответ 00301 🤔
+ 1
If you have still in confusion,
As already explained by @Maria Vasilyova, at indexes 0,1,3 are set to zero, remainging values at indexes 2,4 are unchanged..
So the answer is 00301
+ 1
After each iteration of the array "а", the campaign changes:
1. a[1]=0 => a={1, 0, 3, 4, 1}
2. a[0]=0 => a={0, 0, 3, 4, 1}
3. a[3]=0 => a={0, 0, 3, 0, 1}
4. a[1]=0 => a={0, 0, 3, 0, 1}
So output is 00301
At first I thought that iterations are much more, but I was wrong ...
https://code.sololearn.com/cZ6fCO7efl5d/?ref=app
+ 1
Hi Vasiliy someone asked the same doubt some time back. I have explained it in the code below.
https://code.sololearn.com/c0pij3z7g868/?ref=app
0
Line-1: int[]={1,2,3,4,1}
you have declared an integer variable "a" whose length is "5"
Line-2: for (int n: a)
Here we are reading an array elements and storing it in the variable "n" using for iteration one by one till the end of the array "a".
Line -3: a[n] = 0;
In this line the variable " n" which contains the element of the array now becomes the index of the array.
When Line -2 and Line-3 gets executed the array becomes
a[1]=0;
a[0]=0;
a[3]=0;
a[0]=0;
a[1]=0;
Now the array becomes
a={0,0,3,0,1}
Line-4: for (int n: a)
System.out.println(n);
The out put of this program is:
0
0
3
0
1
0
When this 2 line executes
for(int n: a);
a[n]=0;
The array "a" gets modified
a[1]=0;
a[0]=0;
a[3]=0;
a[0]=0;
a[1]=0;
When you print the array "a".
The out put will be.
0
0
3
0
1