Tower of Hanoi Problem implementation in C
Tower of Hanoi is a classical problem in operating system. It has rods and disks. To arrange it in a particular order, this program is used.
Steps to follow:
- Create a function towerofHanoi()with four parameters. No- number of disks, source and auxiliary and destination.
- First, the control moves no-1 disks to the auxiliary rod.
- Next, it moves the largest disk to the destination.
- At last, it moves the no-1 disks from auxiliary to destination.
C Program:
#include <stdio.h>
void towerofHanoi(int no, char src, char auxi, char dest) {
if (no == 1) {
printf("Move disk 1 from %c to %c\n", src, dest);
return;
}
towerofHanoi(no -
1, src, dest, auxi);
printf("Move
disk %d from %c to %c\n", no, src, dest);
towerofHanoi(no -
1, auxi, src, dest);
}
int nDisks;
scanf("%d", &nDisks);
towerofHanoi(nDisks, 'X', 'Y', 'Z');
// where X = source, Y =
auxiliary, Z = destination
}
Output:
Enter the number of disks: 4
The Steps to solve Tower of Hanoi with 4 disks:
Move disk 1 from X to Y
Move disk 2 from X to Z
Move disk 1 from Y to Z
Move disk 3 from X to Y
Move disk 1 from Z to X
Move disk 2 from Z to Y
Move disk 1 from X to Y
Move disk 4 from X to Z
Move disk 1 from Y to Z
Move disk 2 from Y to X
Move disk 1 from Z to X
Move disk 3 from Y to Z
Move disk 1 from X to Y
Move disk 2 from X to Z
Move disk 1 from Y to Z
That’s it. The C program to implement tower of Hanoi is done.
Hope, this code is useful to you. Keep Coding!!!!
Comments
Post a Comment