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);
}- A. 3 1
- B. 2 2
- C. 3 5
- 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
- What is printed? c #include <stdio.h> void f(int n) { if (n <= 0) { printf("B "); return; } if (n % 2 == 0) printf("E%d ", n); else…
- What is printed? c #include <stdio.h> int digitSum(int n) { if (n == 0) return 0; printf("%d ", n % 10); return n % 10 + digitSum(n / 10)…
- What is printed? c #include <stdio.h> void count(int n) { int local = n; if (n == 0) { printf("local=%d ", local); return; } count(n - 1)…
- What is printed? c #include <stdio.h> int f(int n); int g(int n) { if (n <= 0) return n; return f(n - 2); } int f(int n) { if (n <= 0)…
- What is printed? c #include <stdio.h> int odds = 0; void f(int n) { if (n == 0) return; if (!(n % 2)) { f(n - 1); return; } odds++; f(n…
- What is printed? c int calls = 0; int fib(int n) { calls++; if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main(void) { int r…