?
What is the value of a[1] after the following code is executed?
What is the value of a[1] after the following code is executed?
int[] a = {0, 2, 4, 1, 3};
for(int i = 0; i < a.length; i++)
a[i] = a[(a[i] + 3) % a.length];
int[] a = {0, 2, 4, 1, 3};
for(int i = 0; i < a.length; i++)
a[i] = a[(a[i] + 3) % a.length];
Answer & Solution
Correct Answer:
Option
B
Here's an explanation of the code:
1. The array
2. The
3. Inside the loop, the value of
(i) For
(ii) For
(iii) For
(iv) For
(v) For
4. After the loop finishes, the modified array
5. Finally, the code prints the value of
Therefore, the output of the code is 1.
1. The array
a is initialized with values: {0, 2, 4, 1, 3}.2. The
for loop iterates over each element of the array using the variable i.3. Inside the loop, the value of
a[i] is updated using the expression a[(a[i] + 3) % a.length].(i) For
i = 0, a[i] is 0. So, a[(0 + 3) % 5] becomes a[3 % 5] which is a[3] (value 1).(ii) For
i = 1, a[i] is 2. So, a[(2 + 3) % 5] becomes a[5 % 5] which is a[0] (value 0).(iii) For
i = 2, a[i] is 4. So, a[(4 + 3) % 5] becomes a[7 % 5] which is a[2] (value 4).(iv) For
i = 3, a[i] is 1. So, a[(1 + 3) % 5] becomes a[4 % 5] which is a[4] (value 3).(v) For
i = 4, a[i] is 3. So, a[(3 + 3) % 5] becomes a[6 % 5] which is a[1] (value 2).4. After the loop finishes, the modified array
a becomes {0, 1, 4, 3, 2}.5. Finally, the code prints the value of
a[1] using System.out.println(a[1]), which outputs 1.Therefore, the output of the code is 1.
Join the Discussion
Login to post a comment or share your explanation.
Logina[1]=a[(a[1]+3)%5]
a[1]=a[(2+3)%5]
a[1]=a[5%5] , but 5%5=0
a[1]=a[0]
a[1]=0
a[i]=a[(a[i]+3)%a.length] //a.length =5;
a[0]=a[(a[0]+3)%5];
a[0]=a[(0+3)%5];//3
a[0]=a[3]; //1
a[1]=a[(a[1]+3)%5];
a[1]=a[(2+3)%5];
a[1]=a[0];
a[1]=1;