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];
A. 0
B. 1
C. 2
D. 3
E. 4
Answer: Option B
Solution(By Examveda Team)
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.
Join The Discussion
Comments ( 5 )
Related Questions on Array
In Java, arrays are objects of which class?
A. Array
B. Collection
C. ArrayList
D. None of the above
How do you declare a one-dimensional array in Java?
A. int[] myArray;
B. int myArray[];
C. Array
D. All of the above
What is the default initial value of numeric elements in an array of type int in Java?
A. 0
B. 1
C. -1
D. Null
What is the correct way to initialize a two-dimensional array in Java?
A. int[][] myArray = {{1, 2}, {3, 4}};
B. int[2][2] myArray = {{1, 2}, {3, 4}};
C. int[2][2] myArray; myArray[0][0] = 1; myArray[0][1] = 2; myArray[1][0] = 3; myArray[1][1] = 4;
D. None of the above
You written wrong answer it must be ArrayIndexOutOfBounds exception check the program
Answer should be 0
I cannot get these the answer should be zero. How can we write 1?
when i=0
a[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
when i=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;