+ 1
Why these codes have these outputs ? output: 0 0 3 0 1
int [] a={1,2,3,4,1}; for(int n: a) a[n]=0; for(int n: a) System.out.println(n);
2 Respuestas
+ 7
Puriya ghazi mir saeed this happen in the same way like my answer in this post
array changes after each iteration and therefore value of variable n changes. So the value of n will be changing according to the elements present at array.
So n = [1, 2, 3, 4, 1]
A = [1, 2, 3, 4, 1]
When n=1:-
A[1] = 0
So now array index 1 become 0 so array A= [1, 0, 3, 4, 1]
n =1 is accessed so now next index and element which n=0 so it will be used for array iteration n=0
A[0] = 0
So A = [0, 0, 3, 4, 1]
Now the next array element and index is 2 so n = 3 is in iteration
A[3] = 0
So array element 4th change to 0
So now A = [0, 0, 3, 0, 1]
Now next iteration for index 3 is 0 so value of n = 0 so again 0th index value in array A will set to 0
A[0] = 0
So array A will become
A = [0, 0, 3, 0, 1]
Now only index 4th and last element is need to be traversed which is n = 1 so now again A[1] will set to 0 which is also already set so
A[1] = 0
So A = [0, 0, 3, 0 1] as final output
https://www.sololearn.com/Discuss/2083124/?ref=app
0
Thank you