You cannot copy content of this page.

Program to solve Towers of Hanoi problem

Program to solve Towers of Hanoi problem



Recursion

Program to solve Towers of Hanoi problem

#include <stdio.h>
#include <conio.h>

void hanoi(int num_disks,char *src,char *tmp,char *trgt);

void main()
{
int disks;
char source[10],temp[10],target[10];
clrscr();
printf(“nEnter total number of disks?”);
scanf(“%d”,&disks);
printf(“nEnter source pillar?”);
scanf(“%s”,source);
printf(“nEnter intermediate pillar?”);
scanf(“%s”,temp);
printf(“nEnter target pillar?”);
scanf(“%s”,target);
hanoi(disks,source,temp,target);
getch();
}



void hanoi(int num_disks,char *src,char *tmp,char *trgt)
{
if(num_disks==1)
{printf(“nMove disk from %s to %s”,src,trgt);
}
else
{
hanoi(num_disks-1,src,trgt,tmp);
printf(“nMove disk from %s to %s”,src,trgt);
hanoi(num_disks-1,tmp,src,trgt);
}
}



Output:

Enter total number of disks?3

Enter source pillar?First

Enter intermediate pillar?Second

Enter target pillar?Third

Move disk from First to Third
Move disk from First to Second
Move disk from Third to Second
Move disk from First to Third
Move disk from Second to First
Move disk from Second to Third
Move disk from First to Third



Comments are closed
x Close

Like Us On Facebook