Towers of Hanoi

ehsano's Avatar, Join Date: Nov 2010
Light Poster
this is
Towers of Hanoi in c++

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's Avatar, Join Date: Nov 2009
Pro contributor
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;
}