Home / Programs / Program to solve Tower of Hanoi problem using recursion
Programming Example

Program to solve Tower of Hanoi problem using recursion

👁 776 Views
💻 Practical Program
📘 Step by Step Learning
Program to solve Tower of Hanoi problem using recursion

Program Code

#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( )*/

Output

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 . . .

Explanation

Program to solve Tower of Hanoi problem using recursion

How to learn from this program

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.