0

How the second for loop works in below program

public class Program { public static void main(String[] args) { int numbers[] = { 1,2,3,4,1}; for( int i:numbers) numbers[i] = 0 ; for( int i:numbers) System.out.println(i) ; } }

17th Feb 2023, 5:43 PM
Rahul
Rahul - avatar
10 odpowiedzi
+ 2
1) numbers[0] = 1 but numbers[0] = 0 sout(0) 2)numbers[1]=2 but numbers[i=1]= 0 sout(0) 3)numbers[2]=3 but numbers[i=2]=3 sout(3) 4)numbers[3]=4 but numbers[i=3]=0 sout(0) 5)numbers[4]=1 but numbers[i=4]=1 sout(1) I hope you understand
17th Feb 2023, 10:39 PM
Carlos
+ 2
Pay attention to the first loop: The element at i is replaced with 0. Again, i is the element, not the index.
17th Feb 2023, 5:52 PM
Lisa
Lisa - avatar
+ 1
The second loop works just like the first loop. For each i in numbers, i is printed.
17th Feb 2023, 5:47 PM
Lisa
Lisa - avatar
+ 1
how? can u elaborate the answer ? 00301 why this is answer
17th Feb 2023, 5:49 PM
Rahul
Rahul - avatar
+ 1
For each i in numbers, i is printed. i is the element in the array.
17th Feb 2023, 5:50 PM
Lisa
Lisa - avatar
+ 1
why answer is 00301
17th Feb 2023, 5:51 PM
Rahul
Rahul - avatar
+ 1
answer should be 00000
17th Feb 2023, 5:51 PM
Rahul
Rahul - avatar
+ 1
not understood !!! plz help me
17th Feb 2023, 5:53 PM
Rahul
Rahul - avatar
+ 1
if you want 0000 you should NOT use for(int i:numbers) this will give you values, not indices. you should use for(int i=0;i<numbers.length;++i) then you can use numbers[i]=0; in a way that makes more sense. public class Program { public static void main(String[] args) { int numbers[] = { 1,2,3,4,1}; for(int i=0;i<numbers.length;++i) numbers[i] = 0 ; for( int i:numbers) System.out.print(i) ; } }
18th Feb 2023, 5:02 AM
Bob_Li
Bob_Li - avatar
+ 1
Inside loops always completes before returning back to the outer loop for example Loop1(2times) Loop2(3times) Loop1 (outside loop) Looo2 Looo2 Looo2 Loop1 (back to outside loop) Loop2 Loop2 Loop2 Finished
18th Feb 2023, 11:00 AM
D_Stark
D_Stark - avatar