Examveda
Examveda

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

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.

This Question Belongs to Java Program >> Array

Join The Discussion

Comments ( 5 )

  1. Mohammed Rashad
    Mohammed Rashad :
    11 months ago

    You written wrong answer it must be ArrayIndexOutOfBounds exception check the program

  2. Aditya Vaste
    Aditya Vaste :
    2 years ago

    Answer should be 0

  3. Samarpan Das
    Samarpan Das :
    5 years ago

    I cannot get these the answer should be zero. How can we write 1?

  4. Zeleke Guangul
    Zeleke Guangul :
    7 years ago

    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

  5. Mukesh Mandiwal
    Mukesh Mandiwal :
    8 years ago

    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;

Related Questions on Array