Developing Algorithms Using Arrays

AP Computer Science A· difficulty 5/5

int[] a = {1, 2, 3, 4};
for (int i = 0; i < a.length - 1; i++) {
  a[i + 1] = a[i];
}
System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+a[3]);

What is printed?

  • A

    1 1 1 1

    check_circle
  • B

    1 2 3 4

  • C

    0 1 2 3

  • D

    2 3 4 4

Explanation

Going forward, a[1]=a[0]=1, then a[2]=a[1]=1, then a[3]=a[2]=1. Each subsequent element is overwritten by the (already changed) value to its left, propagating 1 throughout. To shift right correctly, iterate backward.

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

Related questions