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]);
}- A. 3 7 10 19 28
- B. 10 3 7 28 19
- C. 7 3 10 19 28
- 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
- What is printed? c #include <stdio.h> #include <string.h> int main(void) { char names[] = {"x", "yy", "zzz"}; char pp = names + 1…
- What is printed? c #include <stdio.h> int main(void) { int a[3] = {1, 2, 3}, b[3] = {4, 5, 6}; int ptr[2] = {a, b}; int (pa)[3] = &b…
- What is printed? c #include <stdio.h> int main(void) { unsigned n = 37; printf("%u", n ^ (n >> 1)); }
- What is printed? c #include <stdio.h> int main(void) { int x = -8; printf("%d", x / 2 + x % 3); }
- What is printed? c #include <stdio.h> int calls = 0; int bs(const int a, int lo, int hi, int k) { calls++; if (lo > hi) return -1; int m =…
- What is printed? Assume short is 2 bytes, int is 4 bytes and both use natural alignment. c #include <stdio.h> struct S { char c; short s…