Tower of Hanoi
Sure, here's a C program to solve the Tower of Hanoi problem using recursion:
cpp
Copy code
#include <stdio.h>
void move(int n, char from, char to, char aux) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
move(n-1, from, aux, to);
printf("Move disk %d from %c to %c\n", n, from, to);
move(n-1, aux, to, from);
}
int main() {
int n;
printf("Enter number of disks: ");
scanf("%d", &n);
move(n, 'A', 'C', 'B');
return 0;
}
Here's how the program works:
The move function takes three parameters: the number of disks n, the starting peg from, the target peg to, and the auxiliary peg aux.
If there is only one disk to move (n == 1), we print a message indicating that we're moving the disk from from to to.
Otherwise, we recursively call move with n-1 disks, moving them from the starting peg from to the auxiliary peg aux, using the target peg to as an auxiliary.
After the recursive call, we print a message indicating that we're moving the largest disk from from to to.
Finally, we recursively call move with `n
Comments
Post a Comment