C Program to implement Tower of Hanoi
Program
#include<stdio.h>
void tower(int, char, char, char);
void main()
{
int n;
printf("Enter the number of disks to be moved\n");
scanf("%d", &n);
printf("Movement of disks:\n");
tower(n, 'A', 'B', 'C');
}
void tower(int n, char source, char aux, char destination)
{
if(n == 1)
{
printf("Moving disk 1 from %c to %c\n", source, destination);
return;
}
tower(n - 1, source, destination, aux);
printf("Moving disk %d from %c to %c\n", n, source, destination);
tower(n - 1, aux, source, destination);
}
Output 1
Enter the number of disks to be moved
3
Movement of disks:
Moving disk 1 from A to C
Moving disk 2 from A to B
Moving disk 1 from C to B
Moving disk 3 from A to C
Moving disk 1 from B to A
Moving disk 2 from B to C
Moving disk 1 from A to C
Output 2
Enter the number of disks to be moved
1
Movement of disks:
Moving disk 1 from A to C