GATE Computer ScienceHardGATE CS (PYQ pattern)

int a[] = {1, 3, 4, 6, 8, 9, 11, 14}; int i = 0, j = 7, c = 0, it = 0; while (i < j) { it++; if (a[i] + a[j] > 15) { c += j - i; j--; } else i++; } printf("%d %d", c, it); What is printed?

  1. A. 13 7
  2. B. 7 7
  3. C. 10 7
  4. D. 10 8

Correct answer: C. 10 7

When a[i] + a[j] > 15, every index from i to j - 1 pairs with j to exceed 15 (the array is sorted), so j - i pairs are counted at once and j retires; otherwise a[i] is too small for every remaining partner and i retires. Exactly one index retires per iteration, so it = 7 and c is the number of pairs with sum above 15, which is 10 (a brute-force count agrees). Using >= 15 would give 13.

More Programming and Data Structures (GATE) questions

Exams that ask this topic