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);
}
  1. A. 0 3
  2. B. 0 2
  3. C. 0 4
  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

Exams that ask this topic