logo CodeStepByStep logo


Language/Type: C++ recursion
Author: Marty Stepp (on 2016/06/16)

The Towers of Hanoi is a game where you have three pegs (#1, #2, and #3) and some circular disks of different sizes that slide onto the pegs. They all start on one peg, largest to smallest (largest on the bottom). The goal is to move all the disks to another peg by following these rules: you may only move one disk at a time from peg to peg; no disk may be placed on top of a smaller disk.


Write a recursive function named hanoi that prints a solution to the classic Towers of Hanoi puzzle. Your function should accept three integer parameters representing the number of disks, the starting peg number, and ending peg number. Your function should print the solution to the game to move from the given start peg to the given end peg. For example, the call of hanoi(3, 1, 3); should print the following output to move the three pegs from peg #1 to peg #3:

move disk 1 from peg 1 to peg 3
move disk 2 from peg 1 to peg 2
move disk 1 from peg 3 to peg 2
move disk 3 from peg 1 to peg 3
move disk 1 from peg 2 to peg 1
move disk 2 from peg 2 to peg 3
move disk 1 from peg 1 to peg 3

Constraints: Your solution should be recursive and should not use any loops or data structures.

Type your solution here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.