ProgrammingModerateProduct company OA

What is printed?

What is printed?
int cmp(const void *a, const void *b) {
    return *(const int *)b - *(const int *)a;
}
int main(void) {
    int v[] = {4, 9, 1, 7};
    qsort(v, 4, sizeof v[0], cmp);
    printf("%d %d", v[0], v[3]);
}
  1. A. 1 9
  2. B. 9 1
  3. C. 4 7
  4. D. 9 4

Correct answer: B. 9 1

qsort puts a before b when the comparator returns a negative value. Computing b − a (rather than a − b) reverses the usual order, so the array is sorted descending: 9 7 4 1. (Subtraction is safe here only because the values are small.)

More C Programming questions

Exams that ask this topic