ProgrammingVery hardCompetitive coding (CP)

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;
    int dx = ds(x), dy = ds(y);
    if (dx != dy) return dx - dy;
    return (x > y) - (x < y);
}
int main(void) {
    int v[] = {19, 7, 28, 3, 10};
    qsort(v, 5, sizeof v[0], cmp);
    for (int i = 0; i < 5; i++) printf("%d ", v[i]);
}
  1. A. 3 7 10 19 28
  2. B. 10 3 7 28 19
  3. C. 7 3 10 19 28
  4. D. 10 3 7 19 28

Correct answer: D. 10 3 7 19 28

Digit sums are 10, 7, 10, 3 and 1, so the order is by digit sum first: 10, then 3, 7, and the two sums of 10 are broken by value, giving 19 before 28. Ordering by raw value alone gives 3 7 10 19 28.

More C Programming questions

Exams that ask this topic