i am learning about recursion in c++ but have been stumped by the following c++ code used to solve the Tower Of Hanoi problem.
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 problem is i don't understand how the recursion is working. why doe m go to 1 before it executes the "if" statement? how does m go back to 2?