in reply to Recursion Confusion

When hanoi is called with $n > 1, the code in the else clause runs as follows:

  1. first recursive call with $n - 1
  2. The print statement you say “does not make sense”
  3. second recursive call with $n - 1

Update: My initial explanation with $n == 3 was wrong. Simpler to let $n == 2:

So with $n initially set at 2, (1) is executed. It recursively calls hanoi with $n == 1. At this point the if clause executes, and the function returns. Next, (2) produces the output that is confusing you. Then (3) produces another recursion; when this returns, the initial call to hanoi also returns, and the function is complete.

(Where I got confused earlier:) For each recursive call to hanoi where $n > 2, an additional else clause comes into play, adding its own print statement to the output.

Perhaps this helps: Every output statement where $n == 1 is written by the print statement in the if clause. Every other output statement (where $n > 1) is written by the print statement sandwiched between the two recursive calls in the else clause.

Clear now? ;-)

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,