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

🖥 Program 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
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.