5/01/2009

C Program Tower Of Hanoi


/*C Program Tower Of Hanoi*/
#include<stdio.h>
#include<conio.h>
void TOH(int,char,char,char);
void main()
{
    int n;

    printf("Enter number of disks:\n");
    scanf("%d",&n);
    printf("Tower of Hanoi for %d disk:\n",n);
    TOH(n,'a','b','c');

}
void TOH(int n,char a,char b,char c)
{
    if(n<=0)
        printf(" wrong i/p \n");
    else if(n==1)
        printf(" move disk from tower %c to %c \n",a,c);
    else
    {
        TOH(n-1,a,c,b);
        TOH(1,a,b,c);
        TOH(n-1,b,a,c);
    }
}
Out Put:
Enter number of disks:
3
Tower of Hanoi for 3 disk:
 move disk from tower a to c
 move disk from tower a to b
 move disk from tower c to b
 move disk from tower a to c
 move disk from tower b to a
 move disk from tower b to c
 move disk from tower a to c

No comments:

Post a Comment