Tower of Hanoi

I'm looking at the code for the Tower of Hanoi. If you're not familiar with the problem, here's a wiki article on it:
http://en.wikipedia.org/wiki/Tower_of_Hanoi

You can see in the code I printed out "n == ___" The problem is I don't get why
n == 1 on the first print out. I thought it would first cout through the else conditional and it would be n == 2. Why does n == 1?
I got the code from a book, so the comments are sparse since I'm obviously a little in the dark about how it works.
Thanks in advance.



#include <iostream>
using namespace std;
void move_rings(int n, int src, int dest, int other)//recursive form of moving discs
{
if (n==1)
{cout << "1Move from " << src << " to " << dest << " n = " << n << " src = " << src << " dest = " << dest << " other = " << other << endl;
}
else
{move_rings(n-1, src, other, dest);
cout << "2Move from " << src << " to " << dest << " n = " << n << " src = " << src << " dest = " << dest << " other = " << other << endl;
move_rings(n-1, other, dest, src);
}
}

int main()
{
int n = 3;//3 discs to move among three pegs
move_rings(n,1,3,2);
return 0;
}

In your else case, the first line is move_rings(n-1, src, other, dest);
This will cause move_rings to be called recursively until we hit n=1 at which point it enters the if case and prints the mentioned statement.
It would make more sense if you would construct a class for your Tower of Hanoi game; and the methods of the class would contain movements, conditions and solution to the game.
Thanks saurav2031. I get what you're saying about n subtracting from itself until it is printed by the if statment. But then why does n then add to itself and go from 1 to 2 or even 3?
Also from my point of view it seems that it should always finish out the else statement and print and then subtract 1 from n again. And from what you're saying with the subtraction it seems to me like it would only print when n ==1, and never print from the else statement. Thanks for any explanation on this.
1) u r calling move_rings(3, ...) from main
2) This goes to the else case of move_rings and calls move_rings(2, ...)
3) This again goes to the else case and calls move_rings(1, ...)
4) Now we enter the if statement of move_rings and the cout is called. After this cout the move_rings(1, ...) returns to its caller function which was move_rings(2, ...) which now calls the cout with n=2 and so on

Hope this helps u understand.
Topic archived. No new replies allowed.