ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer moves = 0
Function hanoi(Integer n)
    if (n == 0)
        return
    end if
    hanoi(n - 1)
    moves = moves + 1
    hanoi(n - 1)
End Function

hanoi(4)
Print moves
  1. A. 16
  2. B. 15
  3. C. 7
  4. D. 31

Correct answer: B. 15

This counts the classic Tower-of-Hanoi move formula: moves(n) = 2*moves(n-1)+1, which for n disks equals 2^n - 1. For n=4, that is 2^4 - 1 = 15.

More Pseudocode and Code Tracing questions

Exams that ask this topic