".C" file is available in downloadable format at :
(Open the link and click on the download arrow on the top right to download the file.)
Given below is the code for C program for Tower of Hanoi problem using recursion:
-----------------------------------------------------------------------------------
#include<stdio.h>
int tower_of_hanoi(int no_of_disks, char source, char helper, char final)
{
if(no_of_disks == 1)
{
printf("\nMove Disk %d From %c To %c\n", no_of_disks, source, final);
return 0;
}
tower_of_hanoi(no_of_disks - 1, source, final, helper);
printf("Move Disk %d From %c To %c\n", no_of_disks, source, final);
tower_of_hanoi(no_of_disks - 1, helper, source, final);
return 0;
}
int main()
{
char source = 'A', helper = 'B', final = 'C';
int no_of_disks;
printf("\nEnter The Number of Disks:\t");
scanf("%d", &no_of_disks);
printf("\nSequence of Disks:\n");
tower_of_hanoi(no_of_disks, source, helper, final);
printf("\n");
return 0;
}
int tower_of_hanoi(int no_of_disks, char source, char helper, char final)
{
if(no_of_disks == 1)
{
printf("\nMove Disk %d From %c To %c\n", no_of_disks, source, final);
return 0;
}
tower_of_hanoi(no_of_disks - 1, source, final, helper);
printf("Move Disk %d From %c To %c\n", no_of_disks, source, final);
tower_of_hanoi(no_of_disks - 1, helper, source, final);
return 0;
}
int main()
{
char source = 'A', helper = 'B', final = 'C';
int no_of_disks;
printf("\nEnter The Number of Disks:\t");
scanf("%d", &no_of_disks);
printf("\nSequence of Disks:\n");
tower_of_hanoi(no_of_disks, source, helper, final);
printf("\n");
return 0;
}
-----------------------------------------------------------------------------------
No comments:
Post a Comment