Programming Example
Program to solve Tower of Hanoi problem using recursion
Program to solve Tower of Hanoi problem using recursion
#include<stdio.h>
void tofh(int ndisk, char source, char temp, char dest);
main( )
{
char source = 'A', temp = 'B', dest = 'C';
int ndisk;
printf("Enter the number of disks : ");
scanf("%d", &ndisk );
printf("Sequence is :\n");
tofh(ndisk, source, temp, dest);
}/*End of main()*/
void tofh(int ndisk, char source, char temp, char dest)
{
if(ndisk==1)
{
printf("Move Disk %d from %c-->%c\n", ndisk, source, dest);
return;
}
tofh(ndisk-1, source, dest, temp);
printf("Move Disk %d from %c-->%c\n", ndisk, source, dest);
tofh(ndisk-1, temp, source, dest);
}/*End of tofh( )*/
Enter the number of disks : 3
Sequence is :
Move Disk 1 from A-->C
Move Disk 2 from A-->B
Move Disk 1 from C-->B
Move Disk 3 from A-->C
Move Disk 1 from B-->A
Move Disk 2 from B-->C
Move Disk 1 from A-->C
Press any key to continue . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.