ProgrammingHardTCS NQT · Accenture

What is printed?

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

Correct answer: B. 3 1 3 9 1 2

The first key a is sorted descending, so the two rows with a = 3 come first and are ordered by b ascending, then the row with a = 1. The output is 3 1, 3 9, 1 2.

More C Programming questions

Exams that ask this topic