Sunday, 25 September 2011

Tower of Hanoi

#include<stdio.h>
#include<string.h>

int tower(int n, char s, char t, char d)
{
   int x,y;
   if(n<=0) return 0;
   x= tower(n-1,s,d,t);
   printf("move %d from %c to %c\n",n,s,d);
   y=tower(n-1,t,s,d);
   return(x+y+1);
 }

void main()
{
   int n;
   printf("Enter the number of discs\n");
   scanf("%d",&n);
   n= tower(n,'S', 'T','D');
   printf("There are %d moves\n",n);
   getch();
}


This is the code from the text Tanenbaum..a slight modification has been done.


#include<stdio.h>

int tower(int n,char s,char d,char a)
{
 if(n==1)
 {
  printf("Move the disk %d from %c to %c\n",n,s,d);
  return;
 }
 tower(n-1,s,a,d);
 printf("Move the disk %d from %c to %c\n",n,s,d);
 tower(n-1,a,d,s);
}

main()
{
 int n;
 printf("Enter the number of discs:\n");
 scanf("%d",&n);
 printf("The moves are:\n");
 tower(n,'S','D','A');
}

No comments:

Post a Comment