Help understand the iteration | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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);

2nd May 2020, 9:38 AM
Solo
Solo - avatar
10 Answers
+ 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
2nd May 2020, 9:46 AM
Marina Vasilyova
Marina Vasilyova - avatar
+ 3
Хммм интересно
2nd May 2020, 9:53 AM
Marina Vasilyova
Marina Vasilyova - avatar
+ 3
А, понятно, у нас же значения уже поменялись некоторые на ноль, поэтому там такая штука
2nd May 2020, 10:00 AM
Marina Vasilyova
Marina Vasilyova - avatar
+ 3
Vasiliy да, я как обычно не заметила Не люблю такие тесты на внимательность))
2nd May 2020, 10:21 AM
Marina Vasilyova
Marina Vasilyova - avatar
+ 1
Maria Vasilyova, я тоже так подумал ☺️, но нет, правильный ответ 00301 🤔
2nd May 2020, 9:52 AM
Solo
Solo - avatar
+ 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
2nd May 2020, 10:18 AM
Jayakrishna 🇮🇳
+ 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
2nd May 2020, 10:20 AM
Solo
Solo - avatar
+ 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
2nd May 2020, 10:23 AM
Avinesh
Avinesh - avatar
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
2nd May 2020, 2:21 PM
Dasarath Singh
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
3rd May 2020, 8:38 AM
Dasarath Singh