ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int moves = 0;
void h(int n, char from, char via, char to) {
    if (n == 0) return;
    h(n - 1, from, to, via);
    if (++moves == 5) printf("%d:%c->%c ", n, from, to);
    h(n - 1, via, from, to);
}
int main(void) {
    h(3, 'A', 'B', 'C');
    printf("%d", moves);
}
  1. A. 2:B->C 7
  2. B. 1:A->C 7
  3. C. 1:B->A 7
  4. D. 3:A->C 8

Correct answer: C. 1:B->A 7

The 3-disk solution is: 1 A→C, 2 A→B, 1 C→B, 3 A→C, 1 B→A, 2 B→C, 1 A→C. Move 4 is the big disk; move 5 starts the second half, h(2, 'B', 'A', 'C'), whose first step moves disk 1 from B to its 'via' peg A. In total 2^3 − 1 = 7 moves are made.

More C Programming questions

Exams that ask this topic