Hello everyone. I have a question regarding the stack of this programm:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
void hanoi(int n,char a,char b,char c)
{if(n>1)
hanoi(n-1,a,c,b);
cout<<a" "<<b<<endl;
if(n>1)
hanoi(n-1,c,b,a);}
int main()
{int n;
cin>>n;
hanoi(n,'a','b','c');
return 0;}
|
Below are the steps witch i noticed through the stack:
//read n=3
1st call: hanoi(n=3,a='a',b='b',c='c')
2nd call(at line:5): hanoi(n=2,a='a',b='c',c='b')
3nd call(at line:5): hanoi(n=1,a='a',b='b',c='c')
//after that, it goes to 'cout' and it outputs : a b
Next i'm not sure about my logic, but i'll write what i think it happens to the stack so that you can tell me where i mistake:
So, n can not be 1 because ,the next, "if" asks for a "n" more than 1, and as there are no more instructions left after "if", the last segment added to the stack is deleted and n is now n=2.
4th call(at line:8): (n=1,a='b',b='c',c='a')
And hereee is the trouble i'm stuck with.. so. In this appeal, the first instruction that is hit is the first "if". And it is not respected so it should pass to the next instruction after if, which is 'cout()', and print the values of a and b, namely: b c. But this is NOT happening and it prints instead a c. Now i want you to tell me what's that thing which i forgot to take in consideration. Thank you very much!