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[] = {"pear", "fig", "apple", "kiwi", "date"};
    qsort(w, 5, sizeof w[0], cmp);
    for (int i = 0; i < 5; i++) printf("%s ", w[i]);
}
  1. A. fig date pear kiwi apple
  2. B. fig date kiwi pear apple
  3. C. apple date fig kiwi pear
  4. D. fig kiwi date pear apple

Correct answer: B. fig date kiwi pear apple

Shorter words come first, and words of the same length are ordered lexicographically. So fig (3 letters) precedes date, kiwi and pear (4 letters), which precede apple (5 letters).

More C Programming questions

Exams that ask this topic