ProgrammingModerateTCS NQT · Accenture

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (y > x) - (y < x);
}
int main(void) {
    int v[] = {2, 9, 1, 4};
    qsort(v, 4, sizeof v[0], cmp);
    for (int i = 0; i < 4; i++) printf("%d ", v[i]);
}
  1. A. 9 4 2 1
  2. B. 1 2 4 9
  3. C. 4 9 2 1
  4. D. 9 2 4 1

Correct answer: A. 9 4 2 1

The comparator returns a positive value when y is larger than x, so the array ends up in descending order: 9, 4, 2, 1.

More C Programming questions

Exams that ask this topic