## Tower of Hanoi C Program

### write a c program for solve tower of hanoi using recursion.

The basic idea behind the tower of hanoi is if you can solve n-1 cases then you can easily solve the n th cases.

Tower of hanoi is one of the application of stack data structure.

below is c program code to understand tower of hanoi example.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <stdio.h> #include <conio.h> void toh(int, char, char, char); void main() { int n; printf("Enter the number of disk : "); scanf("%d", &n); printf("Here is sequence of moves of tower of hanoi :\n"); toh(n, 'A', 'C', 'B'); } void toh(int no, char source, char destination, char spare) { if (no == 1) { printf("\n move disk 1 from source %c to destination %c", source, destination); return; } toh(no - 1, source, spare, destination); printf("\n move disk %d from source %c to destination %c", no, source, destination); toh(no - 1, spare, destination, source); } |

The out put of tower of hanoi c program is :

1 2 3 4 5 6 7 8 9 10 |
Enter the number of disk : 3 Below are sequence of moves of tower of hanoi : move disk 1 from source A to destination C move disk 2 from source A to destination B move disk 1 from source C to destination B move disk 3 from source A to destination C move disk 1 from source B to destination A move disk 2 from source B to destination C move disk 1 from source A to destination C |