ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
    const char *x = *(const char *const *)a, *y = *(const char *const *)b;
    return x[strlen(x) - 1] - y[strlen(y) - 1];
}
int main(void) {
    const char *w[] = {"abc", "xyz", "bcd", "zab"};
    qsort(w, 4, sizeof w[0], cmp);
    for (int i = 0; i < 4; i++) printf("%s ", w[i]);
}
  1. A. abc bcd xyz zab
  2. B. zab abc bcd xyz
  3. C. xyz zab bcd abc
  4. D. zab bcd abc xyz

Correct answer: B. zab abc bcd xyz

The comparator sorts by the last character of each string: b, c, d, z. So zab (ends in b) comes first and xyz (ends in z) last, and the first letters are not used at all.

More C Programming questions

Exams that ask this topic