W
wahid
• The Tower of Hanoi or Towers of Hanoi is a
mathematical game or puzzle. It consists of three
rods, and a number of disks of different sizes
which can slide onto any rod.
• The objective of the puzzle is to move the entire
stack to another rod, obeying the following rules:
– Only one disk may be moved at a time.
– Each move consists of taking the upper disk from one
of the rods and sliding it onto another rod, on top of
the other disks that may already be present on that
rod.
– No disk may be placed on top of a smaller disk.
• Using recursion, write a program, that would
solve the tower of Hanoi Problem.
• Inputs: Number of Disks, Name of the three
pegs ( Peg on which initially all the disks rest is
input peg, peg on which finally all disks will lie
is output peg, the third peg is the other peg)
(Hint: think recursively, what if there were only two disks?
and what if the N-1 small disks where combined into a single disk?)
Sample Output:
Enter Input peg: 1
Enter output peg :2
Enter other peg : 3
Enter the number of disks :3
Tower of hanoi Solution :
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 1 to Peg 3
Move Disk from Peg 2 to Peg 3
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 3 to Peg 1
Move Disk from Peg 3 to Peg 2
Move Disk from Peg 1 to Peg 2
mathematical game or puzzle. It consists of three
rods, and a number of disks of different sizes
which can slide onto any rod.
• The objective of the puzzle is to move the entire
stack to another rod, obeying the following rules:
– Only one disk may be moved at a time.
– Each move consists of taking the upper disk from one
of the rods and sliding it onto another rod, on top of
the other disks that may already be present on that
rod.
– No disk may be placed on top of a smaller disk.
• Using recursion, write a program, that would
solve the tower of Hanoi Problem.
• Inputs: Number of Disks, Name of the three
pegs ( Peg on which initially all the disks rest is
input peg, peg on which finally all disks will lie
is output peg, the third peg is the other peg)
(Hint: think recursively, what if there were only two disks?
and what if the N-1 small disks where combined into a single disk?)
Sample Output:
Enter Input peg: 1
Enter output peg :2
Enter other peg : 3
Enter the number of disks :3
Tower of hanoi Solution :
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 1 to Peg 3
Move Disk from Peg 2 to Peg 3
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 3 to Peg 1
Move Disk from Peg 3 to Peg 2
Move Disk from Peg 1 to Peg 2