ProgrammingVery hardGATE CS · Product company OA

What is printed?

What is printed?
int a[] = {2, 4, 6, 8, 10, 12, 14}, lo = 0, hi = 6, steps = 0, x = 7;
while (lo <= hi) {
    int m = (lo + hi) / 2;
    steps++;
    if (a[m] == x) break;
    if (a[m] < x) lo = m + 1; else hi = m - 1;
}
printf("%d %d %d", steps, lo, hi);
  1. A. 3 2 2
  2. B. 3 3 3
  3. C. 4 3 2
  4. D. 3 3 2

Correct answer: D. 3 3 2

m = 3 (8 > 7) sets hi = 2; m = 1 (4 < 7) sets lo = 2; m = 2 (6 < 7) sets lo = 3, and lo > hi ends the search. After a failed search lo is the index where x would be inserted (3) and hi = lo − 1.

More C Programming questions

Exams that ask this topic