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.

## C/C++

`#include <stdio.h> ` ` ` `// C recursive function to solve tower of hanoi puzzle ` `void` `towerOfHanoi(` `int` `n, ` `char` `from_rod, ` `char` `to_rod, ` `char` `aux_rod) ` `{ ` ` ` `if` `(n == 1) ` ` ` `{ ` ` ` `printf` `(` `"\n Move disk 1 from rod %c to rod %c"` `, from_rod, to_rod); ` ` ` `return` `; ` ` ` `} ` ` ` `towerOfHanoi(n-1, from_rod, aux_rod, to_rod); ` ` ` `printf` `(` `"\n Move disk %d from rod %c to rod %c"` `, n, from_rod, to_rod); ` ` ` `towerOfHanoi(n-1, aux_rod, to_rod, from_rod); ` `} ` ` ` `int` `main() ` `{ ` ` ` `int` `n = 4; ` `// Number of disks ` ` ` `towerOfHanoi(n, \'A\', \'C\', \'B\'); ` `// A, B and C are names of rods ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

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

Please refer complete article on Program for Tower of Hanoi for more details!

## Recommended Posts:

- C Program for Program to find area of a circle
- C Program for Program for array rotation
- Lex Program to remove comments from C program
- Create Directory or Folder with C/C++ Program
- C Program to Swap two Numbers
- C Program for Bubble Sort on Linked List
- C program to Replace a word in a text by another given word
- C program to invert (making negative) an image content in PGM format
- C Program for Selection Sort
- C Program for Bubble Sort
- C Program for Insertion Sort
- C Program for Radix Sort
- C/C++ Program for n-th Fibonacci number
- C Program for Counting Sort
- C Program for Binary Search (Recursive and Iterative)
- C Program for Min Cost Path
- C/C++ Program for Longest Increasing Subsequence
- C Program for Pancake sorting
- C Program for Binary Insertion Sort
- C Program for Merge Sort