ProgrammingVery hardCompetitive coding (CP)

How many times is disk 3 moved in this recursive Towers of Hanoi with 5 disks? Compute the program output.

How many times is disk 3 moved in this recursive Towers of Hanoi with 5 disks? Compute the program output.
#include <stdio.h>
int cnt = 0;
void h(int n, char f, char t, char v) {
    if (n == 0) return;
    h(n - 1, f, v, t);
    if (n == 3) cnt++;
    h(n - 1, v, t, f);
}
int main(void) {
    h(5, 'A', 'C', 'B');
    printf("%d", cnt);
}
  1. A. 2
  2. B. 8
  3. C. 4
  4. D. 6

Correct answer: C. 4

Disk k moves 2^(n-k) times in an n-disk puzzle, so disk 3 in a 5-disk puzzle moves 2^2 = 4 times. The recursion reaches the n == 3 step exactly once for each such move.

More C Programming questions

Exams that ask this topic