Good day,
I'm having problems seeing how the recursion is working with this program. I've traced it but I don't understand why after if(num >0) is false it returns to the statement following the last function call and then seems to start the recursion again, but backwards? What I see when I trace it is that the program decrements num to zero, it then seems to exit and goes to right after the 2nd to last "}" line 12 in the code fragment but then it return to line 8, why doesn't it just return to the main program?
any help is appreciated.
void moveDiscs(int num, int fromPeg, int toPeg, int tempPeg)
{
if (num > 0)
{//added to watch the variables
cout << "fromPeg: toPeg: tempPeg: " << endl;
cout << " " << fromPeg << " " << toPeg << " " << tempPeg << endl;
moveDiscs (num - 1, fromPeg, tempPeg, toPeg);
cout << "Move a disc from peg " << fromPeg (program then goes to here and calls moveDiscs again at line 10.
<< " to peg " << toPeg << endl;
moveDiscs(num - 1, tempPeg, toPeg, fromPeg);(then here and starts the recursion again)
}
}program goes to here when num >0 fails) it then goes to back to line 8
Here's the program:
// This program displays a solution to the Towers of
// Hanoi game.
#include <iostream>
using namespace std;
// Function prototype
void moveDiscs(int, int, int, int);
int main()
{
const int NUM_DISCS = 3; // Number of discs to move
const int FROM_PEG = 1; // Initial "from" peg
const int TO_PEG = 3; // Initial "to" peg
const int TEMP_PEG = 2; // Initial "temp" peg
// Play the game.
moveDiscs(NUM_DISCS, FROM_PEG, TO_PEG, TEMP_PEG);
cout << "All the pegs are moved!\n";
system("pause");
return 0;
}
void moveDiscs(int num, int fromPeg, int toPeg, int tempPeg)
{
if (num > 0)
{
cout << "fromPeg: toPeg: tempPeg: " << endl;
cout << " " << fromPeg << " " << toPeg << " " << tempPeg << endl;
moveDiscs (num - 1, fromPeg, tempPeg, toPeg);
cout << "Move a disc from peg " << fromPeg
<< " to peg " << toPeg << endl;
moveDiscs(num - 1, tempPeg, toPeg, fromPeg);
}
}