• Using recursion, write a program, that would
solve the tower of Hanoi Problem.
• Inputs: Number of Disks, Name of the three
pegs ( Peg on which initially all the disks rest is
input peg, peg on which finally all disks will lie
is output peg, the third peg is the other peg)
(Hint: think recursively, what if there were only two disks?
and what if the N-1 small disks where combined into a single disk?)
Sample Output:
Enter Input peg: 1
Enter output peg :2
Enter other peg : 3
Enter the number of disks :3
Tower of hanoi Solution :
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 1 to Peg 3
Move Disk from Peg 2 to Peg 3
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 3 to Peg 1
Move Disk from Peg 3 to Peg 2
Move Disk from Peg 1 to Peg 2
#include <stdio.h>
#include <stdlib.h>
int get_positive_number(const char *prompt)
{
int d;
fputs(prompt, stdout);
fflush(stdout);
if(scanf("%d", &d) == 1 && d > 0)
return d;
fputs("Invalid input: needed a positive integer\n", stderr);
exit(1);
}
void hanoi(int n, int x, int y, int z)
{
if(n) {
hanoi(n - 1, x, z, y);
printf("Move disk from peg %d to peg %d\n", x, y);
hanoi(n - 1, z, y, x);
}
}
int main(void)
{
int x, y, z, n;
x = get_positive_number("Enter input peg: ");
y = get_positive_number("Enter output peg: ");
z = get_positive_number("Enter other peg: ");
n = get_positive_number("Enter the number of disks: ");
hanoi(n, x, y, z);
return 0;
}