#include #include void hanoi( char peg1, char peg2, char peg3, int how_many ); main() { char peg1 = 'A', /* origin */ peg2 = 'B', /* destination */ peg3 = 'C'; /* spare */ int how_many; /* number of disks initially on the origin */ /* Prompt for and warn about the number of disks to be moved. */ printf( "\n\tHow many disks initially on peg A?" "\n\tIf more than 7, the solution may seem to " "take forever!\n\t" ); scanf( "%d", &how_many ); /* Anything to move? */ if ( how_many < 1 ) printf( "\n\tThere's nothing to move!" ); /* Otherwise solve with: */ /* -- peg1 as the origin */ /* -- peg2 as the destination */ /* -- peg3 as the spare */ else hanoi( peg1, peg2, peg3, how_many ); return EXIT_SUCCESS; } void hanoi( char p1, char p2, char p3, int how_many ) /* p1 -- origin p2 -- destination p3 -- spare how_many -- number of disks to move */ { /* If there is only 1 disk on p1, then move it to p2 */ /* and quit as the problem is solved. */ if ( how_many == 1 ) { printf( "\n\n\tMove top disk from peg %c to peg %c.", p1, p2 ); return; } /* Otherwise: */ /* (1) Move how_many - 1 disks from p1 to p3: */ /* p1 is the origin, p3 is the destination, */ /* and p2 is the spare. */ /* */ /* (2) Move the top disk from p1 to p2. */ /* */ /* (3) Move how_many - 1 disks from p3 to p2: */ /* p3 is the origin, p2 is the destination, */ /* and p1 is the spare. */ hanoi( p1, p3, p2, how_many - 1 ); printf( "\n\n\tMove top disk from peg %c to peg %c.", p1, p2 ); hanoi( p3, p2, p1, how_many - 1 ); }