# Here I shared C program for tower of hanoi problem using recursion.

The Tower of Hanoi is a mathematical game or puzzle. It consists of a number of disks of different sizes which can slide on any of three rods(pegs). The game starts with the disks arranged in ascending order in stack on one rod but makes sure the smallest at the top all-time and thus making a conical shape as shown in below image.

Aim of the game or puzzle is to move the whole entire stack to another rod, Rules to move all disks over to 3 towers but you can not place a larger disk on a smaller disk but few rules to be followed are −

- Only one disk move at a time.
- Only "
**top**" disk can be removed. - In each movement taking the top disk from one tower to top of another tower but you can not place larger on a smaller disk.

With three disks, the game or puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2

^{n}-1, where n is the number of disks.**Animated solution of the Tower of Hanoi Puzzle**

C program using recursion is given below which finds solution for Tower of Hanoi Problem.

## C Program for Tower of Hanoi Problem Using Recursion

#includevoid hanoi(int n, char source_rod, char dest_rod, char aux_rod); void main() { int n; printf("Enter Number of Disks:\t"); scanf("\n%d",&n); hanoi(n, 'A', 'C', 'B'); return; } void hanoi(int n, char from_rod, char to_rod, char aux_rod) { if(n<=0) { printf("Wrong Number of disk\n"); } else if (n == 1) { printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); return; } else { hanoi(n-1, from_rod, aux_rod, to_rod); printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); hanoi(n-1, aux_rod, to_rod, from_rod); } }

####
**OUTPUT**

Enter Number of Disks: 3

Move disk 1 from rod A to rod C

Move disk 2 from rod A to rod B

Move disk 1 from rod C to rod B

Move disk 3 from rod A to rod C

Move disk 1 from rod B to rod A

Move disk 2 from rod B to rod C

Move disk 1 from rod A to rod C

--------------------------------

NOTE: Comment below if you have doubts or found anything incorrect related to an above program for tower of hanoi in C.