Developing Algorithms Using Arrays

AP Computer Science A· difficulty 4/5

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

What is printed?

  • A

    1 1 4 4

  • B

    1 2 3 4

    check_circle
  • C

    4 3 2 1

  • D

    4 4 1 1

Explanation

Looping all the way to n undoes the swaps in the second half. Each swap is performed twice, restoring the original. Reversal must use n/2.

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

Related questions

AP Computer Science A · Developing Algorithms Using Arrays Practice Question | Acemy