ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
#include <stdio.h>
int cmp = 0;
int search(int *a, int n, int key) {
    if (n == 0) return -1;
    cmp++;
    if (a[n - 1] == key) return n - 1;
    return search(a, n - 1, key);
}
int main(void) {
    int a[5] = {4, 8, 15, 16, 23};
    printf("%d %d", search(a, 5, 16), cmp);
}
  1. A. 3 1
  2. B. 2 2
  3. C. 3 5
  4. D. 3 2

Correct answer: D. 3 2

search checks the array from the back: n=5 compares a[4]=23 (cmp=1, no match), recurses to n=4 which compares a[3]=16 (cmp=2, match), returning index 3 immediately without checking the remaining elements.

More C Programming questions

Exams that ask this topic