ProgrammingVery hardCompetitive coding (CP)
What index is printed when bsearch looks up "cat" in the sorted array {"ant", "bee", "cat", "dog"}?
What index is printed when bsearch looks up "cat" in the sorted array {"ant", "bee", "cat", "dog"}?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *k, const void *e) {
return strcmp((const char *)k, *(const char *const *)e);
}
int main(void) {
const char *w[] = {"ant", "bee", "cat", "dog"};
const char **r = bsearch("cat", w, 4, sizeof w[0], cmp);
printf("%ld", (long)(r - w));
}- A. 1
- B. 3
- C. 2
- D. 0
Correct answer: C. 2
The array is sorted, and bsearch finds "cat" at index 2 after comparing it with "bee" and then "cat".
More C Programming questions
- How many ordered ways are there to write 10 as a sum of 1s, 2s and 3s? Compute with this program. c #include <stdio.h> int f(int n) { if…
- What is printed? c #include <stdio.h> int main(void) { unsigned n = 44; while (n & (n - 1)) n &= n - 1; printf("%u", n); }
- What is printed? c #include <stdio.h> int main(void) { unsigned n = 0; printf("%d", (n & (n - 1)) == 0); }
- What is printed? Assume uint32t is 32 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint32t h = 2166136261u; h ^=…
- What is printed? c #include <stdio.h> #include <stdlib.h> #include <string.h> struct Rec { char name[4]; int score; }; int cmp(const void…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 6; printf("%u", (x >> 1) ^ x); }