Question: So here I have a program that shows the simulation of solving the Hanoi puzzle. My program works fine for the most part but does
So here I have a program that shows the simulation of solving the Hanoi puzzle. My program works fine for the most part but does not terminate when it should. It should terminate once all discs are on the C peg (C C C), but mine continues to a fourth disc which is not given. There should only be three discs. Any help would be appreciated!
//////////////////////////////////////////////////////////////////////////////////////
#include
using namespace std;
const int num = 3;
const char from_peg = 'A';
const char to_peg = 'B';
const char temp_peg = 'C';
char position[num];
void moveDiscs(int num,int disc,char source,char dest, char spare){
if (disc == 0){
position[disc]=dest;
cout<<"Moved disc "<
cout<<" ( ";
for(int i = 0;i
cout<
}
cout<<")"<
}else{
moveDiscs(num,disc-1,source,spare,dest);
position[disc]=dest;
cout<<"Moved disc "<
cout<<" ( ";
for(int i = 0;i
cout<
}
cout<<")"<
moveDiscs(num,disc-1,spare,dest,source);
}
}
int main() {
cout<<"Starting Position for 3 discs are (";
for(int i = 0;i
position[i]='A';
cout<
}
cout<<")"<
moveDiscs(3,3,from_peg,to_peg,temp_peg);
return 0;
}
/////////////////////////////////////////////////////////////////////////
output:
Starting Position for 3 discs are (A A A ) Moved disc 1 to peg C ( C A A ) Moved disc 2 to peg B ( C B A ) Moved disc 1 to peg B ( B B A ) Moved disc 3 to peg C ( B B C ) Moved disc 1 to peg A ( A B C ) Moved disc 2 to peg C ( A C C ) Moved disc 1 to peg C ( C C C ) <--- I need it to stop here Moved disc 4 to peg B ( C C C ) Moved disc 1 to peg B ( B C C ) Moved disc 2 to peg A ( B A C ) Moved disc 1 to peg A ( A A C ) Moved disc 3 to peg B ( A A B ) Moved disc 1 to peg C ( C A B ) Moved disc 2 to peg B ( C B B ) Moved disc 1 to peg B ( B B B )
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
