Q44
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];
A.
0
B.
1
AnswerC.
2
D.
3
E.
4
Answer: Option B
Solution
Answer: Option B
Solution:
Here's an explanation of the code: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.