The Program in C to solve the tower of hanoi problem inputted by user is given below:
#include <stdio.h>
void tower_of_hanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);
return;
}
tower_of_hanoi(n-1, from_rod, aux_rod, to_rod);
printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
tower_of_hanoi(n-1, aux_rod, to_rod, from_rod);
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
tower_of_hanoi(n, 'A', 'C', 'B');
return 0;
}
Output:
Enter the 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
Pro-Tips💡
This program defines a function tower_of_hanoi()
that takes in four parameters: the number of disks n
, and three characters representing the rods ‘A’, ‘B’, ‘C’ .
The function uses recursion to solve the Tower of Hanoi problem. If the number of disks is 1, the function simply prints a message to move the disk from the source rod to the destination rod.
Otherwise, the function first moves the top n-1 disks from the source rod to the auxiliary rod using the destination rod, then prints a message to move the nth disk from the source rod to the destination rod, and finally moves the n-1 disks from the auxiliary rod to the destination rod using the source rod.
In the main function, the program prompts the user to enter the number of disks and calls the tower_of_hanoi()
function with the number of disks, and the rods as arguments.
The function prints the steps required to move all the disks from rod A to rod C using rod B
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.