Program to solve Tower of Hanoi problem using recursion

C Programming Language / Recursion in c

694

Program:

#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

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.