-4

I have this function to solve the Tower of Hanoi problem and fortunately It's working good but can anybody explain to me if the function is calling it self before the cout statement in case m!=0 then how does it ever reach the cout statement or even the other call of itself ??

#include <iostream>

using namespace std;

void Hanoi(int m, char a, char b, char c){
if(m == 1){
    cout << "Move disc " << m << " from " << a << " to " << c << endl;
 }else{  
      Hanoi(m-1, a,c,b);
      cout << "Move disc " << m << " from " << a << " to " << c << endl;
      Hanoi(m-1,b,a,c);
  }
}

int main(){

int discs;
cout << "Enter the number of discs: " << endl;
cin >> discs;
Hanoi(discs, 'A', 'B', 'C');


 return 0;
}
  • 9
    Time to [learn how to debug programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Especially learn how to use a debugger to step through the code, line by line, and stepping into function calls. – Some programmer dude Oct 05 '18 at 11:41
  • @Someprogrammerdude I appreciate the second statement. Complements the blog nicely. – Ron Oct 05 '18 at 11:42
  • 4
    Proper indentation would make this code a lot easier to read. – Borgleader Oct 05 '18 at 11:45
  • That's the "mystery" of recursion. Start with a simpler recursion problem like calculating the factorial of a number recursively. Factorial can be defined recursively like that: `n! = n * (n-1)!` and `n! = 1`. – Jabberwocky Oct 05 '18 at 11:53
  • Recursive functions work exactly like non-recursive functions. You call it, and when it returns you continue where you were. It works in exactly the same way as when `main` continues with `return 0;` after the call to `Hanoi` returns. – molbdnilo Oct 05 '18 at 13:16

1 Answers1

1

Calling Hanoi(m), where m > 1: First it executes Hanoi(m-1) and all resulting calls. Then it executes cout. Then it executes Hanoi(m-1) and all resulting calls a second time.

Consider m == 3:

Hanoi(3)
    Hanoi(2)
        Hanoi(1)
            cout
        cout
        Hanoi(1)
            cout
    cout
    Hanoi(2)
        Hanoi(1)
            cout
        cout
        Hanoi(1)
            cout
VLL
  • 9,634
  • 1
  • 29
  • 54
  • You mean "where `m > 1`" don't you (strict inequality, not weak)? When `m` is `1`, it does not execute `Hanoi(m-1)`, or am I missing something? (Maybe it would be useful to call out "where `m == 1`" as a separate case?) – JaMiT Oct 06 '18 at 01:41