ProgrammingVery hardTCS NQT · Accenture

What is printed?

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

Correct answer: A. 9 31 22 10

Digit sums are 1, 4, 9 and 4. The order is by digit sum descending, and the tie between 22 and 31 is broken by value descending, so 31 comes first.

More C Programming questions

Exams that ask this topic