Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:


1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

[pastacode lang=”c” manual=”%23include%20%3Cstdio.h%3E%0A%20%0A%2F%2F%20C%20recursive%20function%20to%20solve%20tower%20of%20hanoi%20puzzle%0Avoid%20towerOfHanoi(int%20n%2C%20char%20fromrod%2C%20char%20torod%2C%20char%20auxrod)%0A%7B%0A%20%20%20%20if%20(n%20%3D%3D%201)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20printf(%22%5Cn%20Move%20disk%201%20from%20rod%20%25c%20to%20rod%20%25c%22%2C%20fromrod%2C%20torod)%3B%0A%20%20%20%20%20%20%20%20return%3B%0A%20%20%20%20%7D%0A%20%20%20%20towerOfHanoi(n-1%2C%20fromrod%2C%20auxrod%2C%20torod)%3B%0A%20%20%20%20printf(%22%5Cn%20Move%20disk%20%25d%20from%20rod%20%25c%20to%20rod%20%25c%22%2C%20n%2C%20fromrod%2C%20torod)%3B%0A%20%20%20%20towerOfHanoi(n-1%2C%20auxrod%2C%20torod%2C%20fromrod)%3B%0A%7D%0A%20%0Aint%20main()%0A%7B%0A%20%20%20%20int%20n%20%3D%204%3B%20%2F%2F%20Number%20of%20disks%0A%20%20%20%20towerOfHanoi(n%2C%20’A’%2C%20’C’%2C%20’B’)%3B%20%20%2F%2F%20A%2C%20B%20and%20C%20are%20names%20of%20rods%0A%20%20%20%20return%200%3B%0A%7D” message=”C Program” highlight=”” provider=”manual”/]

 

Output:

 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 3 from rod A to rod B
 Move disk 1 from rod C to rod A
 Move disk 2 from rod C to rod B
 Move disk 1 from rod A to rod B
 Move disk 4 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 2 from rod B to rod A
 Move disk 1 from rod C to rod A
 Move disk 3 from rod B to rod C
 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C

 

[ad type=”banner”]