I'm studying about recursion in C++, but the following C++ code used to solve the Tower of Hanoi issue has me baffled.
void Hanoi(int m, string start, string middle, string end){
cout << "m is equal to: " << m << endl;
if(m == 1){
cout << "Move Disc " << " from " << start << " to " << end << endl;
}
else{
Hanoi(m-1,start,end,middle);
cout << "Move disc " << m << " from " << start << " to " << end << endl;
Hanoi(m-1,middle,start,end);
}
}
int main(){
int discs = 3;
Hanoi(discs, "start","middle","end");
}
the output of the code is as follows:
m is equal to: 3
m is equal to: 2
m is equal to: 1
Move Disc from start to end
Move disc 2 from start to middle
m is equal to: 1
Move Disc from end to middle
Move disc 3 from start to end
m is equal to: 2
m is equal to: 1
Move Disc from middle to start
Move disc 2 from middle to end
m is equal to: 1
Move Disc from start to end
My general issue is that I don't understand how the recursion works.
Why does m increment to 1 before executing the "if" statement?
How does m return to 2?