ProgrammingVery hardTCS NQT · Infosys

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person { char name[4]; int age; };
int cmp(const void *a, const void *b) {
    const struct Person *x = a, *y = b;
    if (x->age != y->age) return x->age - y->age;
    return strcmp(x->name, y->name);
}
int main(void) {
    struct Person p[] = {{"ann", 30}, {"bob", 25}, {"cat", 30}, {"dan", 25}};
    qsort(p, 4, sizeof p[0], cmp);
    for (int i = 0; i < 4; i++) printf("%s ", p[i].name);
}
  1. A. bob ann dan cat
  2. B. bob dan ann cat
  3. C. dan bob ann cat
  4. D. bob dan cat ann

Correct answer: B. bob dan ann cat

The age is the primary key and the name breaks ties, so the order is bob, dan (25), then ann, cat (30). Sorting by name alone gives a different order.

More C Programming questions

Exams that ask this topic