ProgrammingVery hardProduct company OA

This prints every permutation of "abc". What is the FIFTH string printed?

This prints every permutation of "abc". What is the FIFTH string printed?
void p(char *s, int k) {
    if (!s[k]) { printf("%s ", s); return; }
    for (int i = k; s[i]; i++) {
        char t = s[k]; s[k] = s[i]; s[i] = t;
        p(s, k + 1);
        t = s[k]; s[k] = s[i]; s[i] = t;
    }
}
/* main: */ char s[] = "abc"; p(s, 0);
  1. A. cab
  2. B. acb
  3. C. cba
  4. D. bca

Correct answer: C. cba

The swap method is not lexicographic. With a first: abc, acb. With b swapped to the front: bac, bca. With c swapped to the front (a and c exchange), the string is cba, which prints first, then cab. So the order is abc acb bac bca cba cab.

More C Programming questions

Exams that ask this topic