ProgrammingHardTCS NQT · Infosys

What is printed?

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

Correct answer: A. 10 7 13 3 17

Elements are ordered by distance from 10, which gives 10 (0), then 7 and 13 (both 3), then 3 and 17 (both 7). Ties are broken by value ascending, so 7 comes before 13 and 3 before 17.

More C Programming questions

Exams that ask this topic