ProgrammingHardTCS NQT · Accenture

What is printed?

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

Correct answer: A. 3 3 5 0 1 2

Rows are sorted by their sum in descending order: {3, 3} has sum 6, {5, 0} has sum 5 and {1, 2} has sum 3. The comparator returns a positive value when the second sum is larger, which gives that order.

More C Programming questions

Exams that ask this topic