Developing Algorithms Using Arrays

AP Computer Science A· difficulty 3/5

int[] a = {1, 2, 3, 4, 5};
int n = a.length;
for (int i = 0; i < n / 2; 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] + " " + a[4]);

What is printed?

  • A

    5 2 3 4 1

  • B

    1 2 3 4 5

  • C

    5 4 1 2 3

  • D

    5 4 3 2 1

    check_circle

Explanation

The standard reverse-array algorithm swaps a[i] with a[n-1-i] for i from 0 to n/2-1. The result is the array reversed: 5 4 3 2 1.

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

Related questions