C-Program for Printing Tower of Hanoi
#include <stdio.h>
//recursive function to exchange the numbers
void tower(int num, char from, char to, char aux)
{
//checking whether the num is equal to one or not
if (num == 1)
{
printf ("\nMove Disk '1' from %c to %c\n", from, to);
return;
}
//calling the function
tower(num -1, from, aux, to);
//it will print from where to where the disk will move
printf ("\nMove Disk '%d' from %c to %c\n", num, from, to);
//again it will call the function
tower (num - 1, aux, to, from);
}
//main program function
int main()
{
//variable declaration
int num;
//Asking user to enter the no of Disks to be entered
printf ("Enter the Total Number of Disks : ");
scanf ("%d", &num);
if (num != 0)
{
printf ("The Move Sequence Involved in the Tower of Hanoi are : ");
//calling the function and passing the disk names
tower(num, 'A', 'C', 'B');
}
else
{
printf ("Error! The Minimum Disk should be more than 1.\n");
}
printf("\n");
return 0;
}
Output:
Have a problem.? Then Discuss in Forums here.

No comments:
Post a Comment