Pages

Towers Of Hanoi Program : Recursion

Towers of Hanoi also called the Tower of Brahma.Towers of Hanoi consists of three rods , rods consists of number of disk different sizes.Disk moved from one rod to another rod.At a time one disk moved.



Program code :

#include<stdio.h>
#include<conio.h>
void hanoi(char,char,char,int);
long int n;
void main()
{
    char p1='A',p2='B',p3='C';
    char ch;
    int nd;
    do{
        clrscr();
        printf("\n \t Enter no of disk:");
        scanf("%d",&nd);
        n=0;
        hanoi(p1,p2,p3,nd);
        printf("\n No of move ment taken to transfer %d disk =%ld\n",nd,n);
        printf("Continue (y/n):");
        ch=getch();
    }while(ch=='y'||ch=='Y');
}
void hanoi(char p1, char p2, char p3, int nd)
{
    if(nd==1)
    {
        n++;
        printf("Move disk-%d from peg -%c to peg-%c\n",nd,p1,p2);
        return;

    }
    hanoi(p1,p2,p3,nd-1);
    n++;
    printf("Move disk %d from peg-%c to peg-%c\n",nd,p1,p2);
    hanoi(p3,p2,p1,nd-1);
}


Output :









If you have any Further Information and Quires about this Article don't hesitate to comment in comment box below.
                                                           AND

 If you like this article , like our Facebook like page and click  +1 to support 123techguide