ProgrammingHardCapgemini · Infosys pattern

How many lines does this pseudocode print for hanoi(5, 'A', 'B', 'C')?

How many lines does this pseudocode print for hanoi(5, 'A', 'B', 'C')?
Function hanoi(Integer n, Char from, Char via, Char to)
    if (n == 0)
        return
    end if
    hanoi(n - 1, from, to, via)
    Print "Move", n, from, to
    hanoi(n - 1, via, from, to)
End Function
  1. A. 31
  2. B. 32
  3. C. 25
  4. D. 63

Correct answer: A. 31

Moves follow M(n) = 2·M(n-1) + 1 with M(0) = 0, so M(n) = 2ⁿ - 1 = 31. 2⁵ = 32 counts one too many, and 63 is M(6).

More Pseudocode and Code Tracing questions

Exams that ask this topic