ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
#include <stdio.h>
#include <string.h>
int main(void) {
    const char *names[] = {"ann", "bob", "cat", "dan", "eve"};
    const char *key = "dan";
    int lo = 0, hi = 4, found = -1;
    while (lo <= hi) {
        int m = (lo + hi) / 2;
        int c = strcmp(names[m], key);
        if (c == 0) { found = m; break; }
        if (c < 0) lo = m + 1;
        else hi = m - 1;
    }
    printf("%d", found);
}
  1. A. 2
  2. B. 4
  3. C. 0
  4. D. 3

Correct answer: D. 3

The binary search compares strings with strcmp, which orders them lexicographically. The middle element at index 2 is cat, which is smaller than dan, so the search moves right and finds dan at index 3.

More C Programming questions

Exams that ask this topic