Solve Tower of Hanoi Problem using Recursion


/*
Write a program to solve Tower of Hanoi problem using recursion.
*/

#include<stdio.h>
 

void tofhanoi(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");
 

tofhanoi(ndisk, source, temp, dest);
}


/*tofhanoi*/
void tofhanoi(int ndisk, char source, char temp, char dest)
{
if(ndisk==1)
{
 

printf("Move Disk %d from %c-->%c\n", ndisk, source, dest);
 

return;
}
tofhanoi(ndisk-1, source, dest, temp);
 

printf("Move Disk %d from %c-->%c\n", ndisk, source, dest);
 

tofhanoi(ndisk-1, temp, source, dest);
}

Post a Comment

0 Comments