Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Towers of Hanoi (http://www.go4expert.com/forums/towers-of-hanoi-t23981/)

ehsano 24Nov2010 22:24

Towers of Hanoi
 
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);
  }
}


virxen 25Nov2010 18:18

Re: Towers of Hanoi
 
your code would be better with the changes i made.

Code:

#include <iostream>
using namespace std;

void hanoi(int n, char A, char B, char C);
int main()
{
    int n=-1;//no need to be global
  while(n<=0){ //generally this is a better practice than using do-while
    cout<<"Enter n= ";
    cin>>n;getchar();//for garbage collecting from input 
  }
  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;
}



All times are GMT +5.5. The time now is 15:38.