Recursive function problem

The problem isn't in code i don't how it works for example the output should be

turn 1:
1->2
turn 2:
turn 1
2->1
turn 2:
turn 1:
1->2
turn 2:
turn 1:
2->1


After it should end becuase moves are now equal to zero but doesnt happen instead it shows strange behaviour


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>
#include<conio.h>
using namespace std;

void ToH(int dskToMv, int cLocation, int tmpLocation)
{
    if (dskToMv!=0)
    {
       cout<<"turn 1\n";
        cout << cLocation << "->" << tmpLocation << endl;
		cout<<"turn 2\n";
		ToH(dskToMv-1,tmpLocation,cLocation);
		cout<<cLocation<<"->"<<tmpLocation<<endl;
		cout<<"turn 3\n";

		cout << cLocation << "->" << tmpLocation << endl;

        
    }
}

int main()
{
    int x;
    cout << "Enter number of disks: ";
    cin >> x;
    ToH(x, 1, 2);
	getch();
    return 0;
}
if disks number is considered 3
it shows strange behaviour

Could you show that?

Would 0<dskToMv be better than dskToMv!=0?
You should remember that your placement of recursive call to function is such that after the recursion is over, the subsequent cout statements will also get executed:
1
2
3
4
5
ToH(dskToMv-1,tmpLocation,cLocation);
		cout<<cLocation<<"->"<<tmpLocation<<endl;
		cout<<"turn 3\n";

		cout << cLocation << "->" << tmpLocation << endl;
keskiverto its the same thing and abhishekm if subseqent cout is executed shouldnt it output turn 3 only once and why does in my guess of output in the last part (turn 2:
turn 1:
2->1) only turn 2 is there and is not inverted this time
No, subsequent statements shall be executed for each of the recursive calls as well ( except the last one ).
They are also part of the function.
so on turn 2 even if its dskToMv =0 it should transfer to turn 3 and turn 3 excecutes consecutive 2 outputs is that right
Topic archived. No new replies allowed.