ProgrammingHardProduct company OA

What is printed?

What is printed?
char *w[] = {"pear", "fig", "apple", "kiwi"};
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3 - i; j++)
        if (strlen(w[j]) > strlen(w[j + 1])) {
            char *t = w[j]; w[j] = w[j + 1]; w[j + 1] = t;
        }
printf("%s %s %s", w[0], w[1], w[3]);
  1. A. fig pear apple
  2. B. fig kiwi apple
  3. C. fig pear kiwi
  4. D. apple pear fig

Correct answer: A. fig pear apple

This bubble-sorts the pointers by string length, swapping only when strictly greater, so equal lengths keep their order (it is stable). Lengths 4, 3, 5, 4 become fig(3), pear(4), kiwi(4), apple(5). 'kiwi' second would need an unstable sort; only pointers move, the strings themselves are untouched.

More C Programming questions

Exams that ask this topic