1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Towers of Hanoi

Discussion in 'C' started by ehsano, Nov 24, 2010.

  1. ehsano

    ehsano New Member

    this is
    Towers of Hanoi in c++:D:D

    Code:
    #include <iostream.h> 
    int n;
    void hanoi(int n, char A, char B, char C);
    void main()
    {
      do { cout<<"Enter n= ";
           cin>>n;
      } while (n<=0);
      hanoi(n,'A','B','C');
    }
    /***************************************************************************************/
    void hanoi(int n, char A, char B, char C)
    {
      if (n==1) cout<<A<<" --> "<<C<<endl;
      else
      { hanoi(n-1,A,C,B);
        cout<<A<<" --> "<<C<<endl;
        hanoi(n-1,B,A,C);
      }
    }
    
     
  2. virxen

    virxen New Member

    your code would be better with the changes i made.

    Code:
    #include <[COLOR=Red]iostream[/COLOR]> 
    using namespace std;
    
    void hanoi(int n, char A, char B, char C);
    [COLOR=Red]int [/COLOR]main()
    {
        [COLOR=Red]int n=-1;[/COLOR]//no need to be global
     [COLOR=Red] while(n<=0){[/COLOR] //generally this is a better practice than using do-while
        cout<<"Enter n= ";
        cin>>n;[COLOR=Red]getchar();[COLOR=Black]//for garbage collecting from input  [/COLOR][/COLOR]
      }
      hanoi(n,'A','B','C');
      getchar();
      return 0;
    }
    /***************************************************************************************/
    void hanoi(int n, char A, char B, char C)
    {
      if (n==1) cout<<A<<" --> "<<C<<endl;
      else
      { hanoi(n-1,A,C,B);
        cout<<A<<" --> "<<C<<endl;
        hanoi(n-1,B,A,C);
      }
    }
    

    and now a second version for the same problem without recursion

    Code:
    #include <stdio.h>
    
    int main(){
        int z,y,n=-1;
        
        while(n<=0){
            printf("\nenter number of disks:");
            scanf("%d",&n);getchar();
        }
        for(y=1;(1<<n)-y;y<<=z-1,printf("disk %i from %i to %i\n",z,(y&y-1)%3,((y|y-1)+1)%3),y++)
            for(z=1;!(y&1);z++,y>>=1);
            getchar();
        return 0;
    }
    
     

Share This Page