Hanoi Tower

Hello everyone. I'm trying to understand the program below witch consists of hanoi tower algorythm or something like that, but i just can't figure out how to pass through it (especially through the stack).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
using namespace std;
void f(int n,char a,char b,char c)
{
    if(n>1)
    f(n-1,a,c,b);
    cout<<a<<" "<<b<<"\n";
    if(n>1)
    f(n-1,c,b,a);
}
int main()
{
    int n;
    cin>>n;
    f(n,'a','b','c');
    return 0;

}

I tried using debugger, call stack, whatchers but i still can't understand. Can you explain me please? Thanks! :)
P.s.: in case of matter, my codeblocks version is 10.05, and my windows 8.1.
http://www.cplusplus.com/articles/D2N36Up4/
It is called recursive function, once you understand that, it'll be easy to understand hanoi tower
another way to look at the code is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
void f(int n,char alphabet1,char alphabet2,char alphabet3)
{
    if(n>1) f(n-1,'a','c','b');
    cout<<alphabet1<<" "<<alphabet2<<"\n";
    if(n>1) f(n-1,'c','b','a');
}
int main()
{
    int n;
    cin>>n;
    f(n,'a','b','c');
    return 0;

}
Last edited on
Topic archived. No new replies allowed.