ProgrammingVery hardCompetitive coding (CP)
What is printed?
What is printed?
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
int x = abs(*(const int *)a), y = abs(*(const int *)b);
return (x > y) - (x < y);
}
int main(void) {
int v[] = {-5, 3, -2, 4, 1};
qsort(v, 5, sizeof v[0], cmp);
for (int i = 0; i < 5; i++) printf("%d ", v[i]);
}- A. -2 1 3 4 -5
- B. 1 -2 3 -5 4
- C. -5 -2 1 3 4
- D. 1 -2 3 4 -5
Correct answer: D. 1 -2 3 4 -5
The comparator orders by absolute value, so the absolute values 1, 2, 3, 4, 5 give 1, -2, 3, 4, -5 with the signs kept. Dropping the signs in the output gives 1 2 3 4 5.
More C Programming questions
- This recursion counts the tilings of a 2 x n board with 2 x 1 dominoes. What is printed? c #include <stdio.h> int ways(int n) { if (n <=…
- What is printed? c #include <stdio.h> int main(void) { int a[] = {1, 2, 3, 5, 7, 8, 9}; int i = 0, j = 6, c = 0; while (i < j) { int s =…
- What is printed? c #include <stdio.h> int main(void) { unsigned lo = 2000000000u, hi = 2500000000u; printf("%u %u", lo + (hi - lo) / 2…
- What is printed? c #include <stdio.h> struct P { int a; int b[3]; }; int main(void) { struct P arr[2] = {{1, {2, 3, 4}}, {5, {6, 7, 8}}}…
- What is printed? c #include <stdio.h> int main(void) { int c = 0; for (unsigned n = 1; n <= 20; n++) { unsigned x = n; int p = 0; while…
- What is printed? c #include <stdio.h> int main(void) { int c = 0; for (unsigned i = 0; i < 8; i++) { unsigned g = i ^ (i >> 1); unsigned x…