ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b) {
    const char *x = *(const char *const *)a, *y = *(const char *const *)b;
    size_t lx = strlen(x), ly = strlen(y);
    if (lx != ly) return lx < ly ? 1 : -1;
    return strcmp(x, y);
}
int main(void) {
    const char *w[] = {"kiwi", "fig", "banana", "plum"};
    qsort(w, 4, sizeof w[0], cmp);
    for (int i = 0; i < 4; i++) printf("%s ", w[i]);
}
  1. A. banana kiwi plum fig
  2. B. banana plum kiwi fig
  3. C. fig kiwi plum banana
  4. D. banana fig kiwi plum

Correct answer: A. banana kiwi plum fig

Longer strings come first, so banana (6) precedes the length-4 words, and fig (3) is last. Among kiwi and plum, strcmp puts kiwi first.

More C Programming questions

Exams that ask this topic