Towers of Hanoi

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

  1. ehsano

    ehsano New Member

    Joined:
    Nov 20, 2010
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    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 Active Member

    Joined:
    Nov 24, 2009
    Messages:
    387
    Likes Received:
    90
    Trophy Points:
    28
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice