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);
}- A. 2
- B. 4
- C. 0
- 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
- What is printed? Assume long long is 64 bits and that the product fits in a long long. c #include <stdio.h> int main(void) { long long p =…
- What is printed? c #include <stdio.h> int clz16(unsigned short x) { int n = 0; while (!(x & 0x8000u)) { x <<= 1; n++; } return n; } int…
- What is printed? Assume ASCII character encoding. c #include <stdio.h> int main(void) { int d = 'z' - 'a'; char e = 'A' + d 2; printf("%d…
- What is printed? c #include <stdio.h> int main(void) { int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; int (p)[3] = m; int q = (int )p + 4…
- What is printed? Assume unsigned short is 16 bits. c #include <stdio.h> int main(void) { unsigned short y = 60000; y += 10000…
- What is printed? c #include <stdio.h> void gen(int d, int v) { if (d == 0) { printf("%d ", v); return; } gen(d - 1, v 2 + 1); gen(d - 1, v…