ProgrammingVery hardTCS NQT · Infosys
What is printed?
What is printed?
#include <stdio.h>
#include <stdlib.h>
struct Item { int id; char tag; };
int cmp(const void *k, const void *e) {
const int *key = k;
const struct Item *it = e;
return (*key > it->id) - (*key < it->id);
}
int main(void) {
struct Item arr[] = {{2, 'a'}, {4, 'b'}, {7, 'c'}, {9, 'd'}, {12, 'e'}};
int key = 7;
struct Item *r = bsearch(&key, arr, 5, sizeof arr[0], cmp);
printf("%ld", (long)(r - arr));
}- A. 1
- B. 2
- C. 3
- D. 4
Correct answer: B. 2
bsearch needs the array sorted by id, which it is, and it returns a pointer to the element with id 7 at index 2. Passing the key in the wrong position would fail, but the comparator here handles it correctly.
More C Programming questions
- What is printed? c #include <stdio.h> int digitsum(unsigned long long n) { return n == 0 ? 0 : (int)(n % 10) + digitsum(n / 10); } int…
- What is printed? Assume uint8t is 8 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint8t x = 3; for (int i = 0; i < 5…
- What is printed? c #include <stdio.h> int main(void) { printf("%d", 07 + 0x10); }
- What is printed? c #include <stdio.h> int main(void) { unsigned mask = ~0u << 4; printf("%X", mask >> 28); }
- How many pairs (i, j) with i < j have a[i] == a[j]? Compute with this program. c #include <stdio.h> int main(void) { int a[] = {1, 2, 3…
- What is printed? c #include <stdio.h> int main(void) { int x = -1; printf("%u", (unsigned)x >> 28); }