#include <iostream>
#include <conio.h>
using namespace std;
void TOH(int d, char tower1, char tower2, char tower3)
{
if(d==1) //base case
{
cout<<"\nShift top disk from tower"<<tower1<<"to tower"<<tower2;
return;
}
TOH(d-1,tower1,tower3,tower2); //recursive function call
cout<<"\nShift top disk from tower"<<tower1<<"to tower"<<tower2;
TOH(d-1,tower3,tower2,tower1); //recursive function call
}
int main()
{
int disk;
cout<<"Enter the number of disks:.";
cin>>disk;
if(disk<1)
cout<<"\nThere are no disks to shift";
else
cout<<"\nThere are "<<disk<<"disks in tower 1\n";
TOH(disk,'1','2','3');
cout<<"\n\n"<<disk<<"disks in tower 1 are shifted to tower 2";
return 0;
}`
/* Enter the number of disk:. 3
/* My understanding...from Main, TOH with its parameters are passed on to void TOH function, then the base case is checked, the if block is skipped as the condition fails since d is 3, then recursive function TOH(d-1 .......tower1) is called....after then I dont get what happens as the output of the function is confusing, more confusing is the argument change from cout function please help.*/
surfingturtle
0
Light Poster
Recommended Answers
Jump to PostHanoi (disks, from_peg, to_peg, spare_peg) if disks == 0 return if disks is 1 { move topmost disk from from_peg to to_peg } else { Hanoi(disks-1, from_peg, spare_peg, to_peg) Hanoi(1, from_peg, to_peg, spare_peg) Hanoi(disks-1, spare_peg, to_peg, from_peg) }
Jump to PostThis is a classic problem in computer science. Basically it is a neat case of induction.
For towers named A,B,C:
Start with a tower of just 1 disk. Transferring it is as easy as moving it from A->C.If you have more than 1 disk its a bit more complicated. …
All 8 Replies
turboscrew
0
Light Poster
Labdabeta
182
Posting Pro in Training
Featured Poster
ddanbe
commented:
For the effort :)
+15
surfingturtle
0
Light Poster
surfingturtle
0
Light Poster
Labdabeta
182
Posting Pro in Training
Featured Poster
surfingturtle
0
Light Poster
Labdabeta
182
Posting Pro in Training
Featured Poster
surfingturtle
0
Light Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.