GATE Computer ScienceVery hardGATE CS (PYQ pattern)

void swap(int *x, int *y) { *x ^= *y; *y ^= *x; *x ^= *y; } int main() { int a[5] = {3, 7, 9, 12, 5}; for (int i = 0; i < 5; i++) swap(&a[i], &a[4 - i]); for (int i = 0; i < 5; i++) printf("%d ", a[i]); } What is printed?

  1. A. 3 7 0 12 5
  2. B. 3 7 9 12 5
  3. C. 5 12 9 7 3
  4. D. 5 12 0 7 3

Correct answer: A. 3 7 0 12 5

The loop runs over the whole array, so pairs (0, 4) and (1, 3) are swapped twice (i = 0, 1 and again at i = 3, 4) and end up in their original places. At i = 2 both pointers name a[2]: *x ^= *y makes it 9 ^ 9 = 0, and the remaining XORs keep it 0. So the array is the original one with the middle zeroed. A temporary-variable swap would have left it unchanged.

More Programming and Data Structures (GATE) questions

Exams that ask this topic