Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 4/5

int[] a = {1, 2, 3, 4, 5};
// remove element at index 1; shift left
for (int i = 1; i < a.length - 1; i++) {
  a[i] = a[i + 1];
}
a[a.length - 1] = 0;
System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]);

What is printed?

  • A

    1 2 3 4 5

  • B

    0 1 3 4 5

  • C

    1 3 4 5 0

    check_circle
  • D

    1 3 4 5 5

Explanation

Removal shifts elements left: a[1]=a[2]=3, a[2]=a[3]=4, a[3]=a[4]=5, then sets a[4]=0 to clear the unused slot.

Want 10 more like this — adaptive to your weak spots?

Related questions