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); } }
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; }