ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
#include <stdio.h>
int total = 0, c1 = 0;
void hanoi(int n, char a, char b, char c) {
    if (n == 0) return;
    hanoi(n - 1, a, c, b);
    total++;
    if (n == 1) c1++;
    hanoi(n - 1, c, b, a);
}
int main(void) {
    hanoi(5, 'A', 'B', 'C');
    printf("%d %d", total, c1);
}
  1. A. 31 15
  2. B. 32 16
  3. C. 30 16
  4. D. 31 16

Correct answer: D. 31 16

Towers of Hanoi with n disks takes 2^n - 1 moves, so 31 for n = 5. Disk 1 moves on every other move, giving 2^(n-1) = 16 times.

More C Programming questions

Exams that ask this topic