PROGRAM TO DEMONSTRATE RECURSION USING SOLUTION OF TOWER OF HANOI.

#include<iostream.h>
int i;

unsigned long int fact(int n)            //FOR FACTORIAL
{                                        //F(N)=N*F(N-1)
if(n<=1)
return 1;
else
return(n*fact(n-1));
}

long int fibb(int n)                     //FOR FIBONACCI SERIES
{
if (n<=1)
return 1;
else
return(fibb(n-1)+fibb(n-2));
}
void hanoi(int n,char source,char inter,char dest)    //FOR TOWERS OF HANOI
{
if(n==1)
cout<<"\n MOVE "<<++i<<": MOVE DISK 1 FROM "<<source<<" TO "<<dest;
else
{
hanoi(n-1,source,dest,inter);
cout<<"\n MOVE "<<++i<<": MOVE DISK "<<n<<" FROM "<<source<<" TO "<<dest;
hanoi(n-1,inter,source,dest);
}
}

void main()               //MAIN() FUNCTION
{
int n;
char ch;
do
{
cout<<"\n                 MAIN MENU"
<<"\n           FIND FACTORIAL        :: 1"
<<"\n           FIND FIBONACCI VALUE  :: 2"
<<"\n           SOLVE TOWER OF HANOI  :: 3"
<<"\n           EXIT                  :: 4"
<<"\n           ENTER UR CHOICE       :: ";
cin>>ch;
switch(ch-48)
{
case 1: do
{
cout<<"\n ENTER THE POSITIVE NO. WHOSE FACTORIAL IS TO BE FOUND ::";
cin>>n;
}while(n<0);
cout<<" fact("<<n<<")="<<fact(n)<<"\n";
break;
case 2: do
{
cout<<"\n ENTER THE POSITIVE NO. WHOSE FIBONACCI VALUE IS TO BE FOUND ::";
cin>>n;
}while(n<0);
cout<<" fibb("<<n<<")="<<fibb(n)<<"\n";
break;
case 3: do
{
cout<<"\n ENTER THE NO. OF DISKS IN TOWER ::";
cin>>n;
}while(n<0);
i=0;
cout<<"\n SOURCE PEG: A , INTERMEDIATE PEG: B , DESTINATION PEG: C";
hanoi(n,'A','B','C');
cout<<"\n\n TOTAL NO. OF MOVES ="<<i;
break;
case 4: cout<<"\n           PROGRAM OVER \n";
break;
default:cout<<"\n           BAD CHOICE \n";
}
}while(ch!='4');
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s