ProgrammingVery hardCompetitive coding (CP)
What is printed?
What is printed?
#include <stdio.h>
int calls = 0;
int bs(const int *a, int lo, int hi, int k) {
calls++;
if (lo > hi) return -1;
int m = (lo + hi) / 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[8] = {0, 1, 2, 3, 4, 5, 6, 7};
int r = bs(a, 0, 7, 0);
printf("%d %d", r, calls);
}- A. 0 3
- B. 0 2
- C. 0 4
- D. 3 3
Correct answer: A. 0 3
The search visits index 3, then index 1, then index 0 where it finds the value 0, which is three calls. The result is index 0.
More C Programming questions
- What is printed? Assume short is 2 bytes, int is 4 bytes and both use natural alignment. c #include <stdio.h> struct S { char c; short s…
- How many steps does this Collatz loop take to reach 1 starting from 27? c #include <stdio.h> int main(void) { unsigned n = 27; int steps =…
- What is printed? c #include <stdio.h> #include <stdlib.h> int cmp(const void a, const void b) { return (const int )a - (const int )b; }…
- What is printed? Assume unsigned int is 32 bits. c #include <stdio.h> int main(void) { int a = -1; unsigned b = 2; printf("%u"…
- What is printed? c #include <stdio.h> int main(void) { unsigned k = 0; int len = -1; printf("%d", k > len); }
- How many integers in 0..15 are a power of two? Compute with this program. c #include <stdio.h> int main(void) { int c = 0; for (unsigned x…