Eternal Eternal - 10 days ago 5
C++ Question

How to count the calls of a recursive function (Increment by 1) | C++

I have the following code as below. It accepts an input and it prints line by line steps to solve the Hanoi problem. All I want to do is to print in each line step1,step2 and so on,from 1 until the end of the steps like the example below:



Enter the number of disks: 3

Step 1: 1-->2 Move one disk from the original peg to the extra peg

Step 2: 1-->3 Move one disk from the original peg to the destination peg

Step 3: 2-->3 Move one disk from the extra peg to the destination peg


#include <iostream>
int count=1;
void ToH(int dskToMv, int cLocation, string orpeg, int tmpLocation, string expeg, int fLocation, string depeg)
{
if( dskToMv != 0 )
{
count++;
ToH( dskToMv-1, cLocation, orpeg, fLocation, depeg, tmpLocation, expeg);
cout<<"Step "<<count<<": Move one disk from the "<< orpeg << " to the " << depeg
<< " " << cLocation << " -> " << fLocation << endl;
ToH( dskToMv-1, tmpLocation, expeg, cLocation, orpeg, fLocation, depeg);
}
}

int main()
{
int c;
cout << "Enter the number of disks: ";
cin >> c;
ToH(c, 1, "original peg ", 2, "extra peg", 3, "destination peg");
}

Answer

Use static variable and increment it after the first function call. The value of the variable persists between successive calls to the function

#include <iostream>



    using namespace std;

    void ToH(int dskToMv, int cLocation, string orpeg, int tmpLocation, string expeg, int fLocation, string depeg)
    {
      static int count=0 ;


         if(dskToMv != 0 ) 
        {


            ToH( dskToMv-1, cLocation, orpeg, fLocation, depeg, tmpLocation, expeg);
          count++;
            cout <<endl<<"Step "<<count<<" "<< cLocation << " --> " << fLocation <<":"<<" Move one disk from the "<< orpeg << " to the " << depeg
               << endl<<endl;
            ToH( dskToMv-1, tmpLocation, expeg, cLocation, orpeg, fLocation, depeg);


        }

    }



    int main()
    {


        int c;
        cout << " Enter the number of disks: ";
        cin >> c;
        ToH(c, 1, "original peg ", 2, "extra peg", 3, "destination peg");


    }