ProgrammingVery hardCompetitive coding (CP)
What is printed?
What is printed?
#include <stdio.h>
int calls = 0;
int bs(int *a, int lo, int hi, int k) {
calls++;
if (lo > hi) return -1;
int m = lo + (hi - lo) / 2;
if (a[m] == k) return m;
return a[m] < k ? bs(a, m + 1, hi, k) : bs(a, lo, m - 1, k);
}
int main(void) {
int a[16];
for (int i = 0; i < 16; i++) a[i] = i;
printf("%d %d", bs(a, 0, 15, 16), calls);
}- A. -1 6
- B. -1 5
- C. -1 7
- D. 16 6
Correct answer: A. -1 6
Key 16 is absent, so the search returns -1 after the recursion reaches an empty range. The six calls cover the intervals [0,15], [8,15], [12,15], [14,15], [15,15] and [16,15].
More C Programming questions
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0; int c = 0; for (unsigned i = 1; i <= 16; i++) { x = i; while (x) {…
- What is printed? c #include <stdio.h> unsigned alt(unsigned x) { unsigned y = x ^ (x >> 1); return (y & (y + 1)) == 0; } int main(void) {…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0xDEADu; printf("%u", (x >> 3) & 0xFu); }
- What is printed? c #include <stdio.h> int main(void) { unsigned a = 0x12345678u, b = 0x12345600u, x = a ^ b; int c = 0; while (x) { c += x…
- What is printed? Assume uint8t is 8 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint8t acc = 0; uint8t v[] = {200…
- What is printed? Assume uint32t is 32 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint32t a = 70000, b = 70000…