Tower of Hanoi Problem Laboratory Experiment #1 Eltayeb Abuelyaman The University of Nizwa College of Arts & Sciences Computer Architecture COMP 233 Summer 2013 Tower of Hanoi Problem Laboratory Experiment #1 Eltayeb Abuelyaman
About the Tower of Hanoi The famous Towers of Hanoi problem has an elegant solution through recursion. In the problem, three pegs, A, B and C exist. ‘n’ disks of differing diameters are placed on peg A so that the larger disk is always below a smaller disk. The objective is to move all the disks to peg C using peg B as auxiliary. Only the top disk on any peg may be moved to any other peg, and the larger disk may never rest on a smaller one.
Laboratory Experiment You task is to write a C++ program that simulate moves of n disks from one peg to another using a third peg as auxiliary. Make sure your code is well written and documented. Due date 25/6/2013 by 10:00 AM.
Hint: Example code The code on the next slide is written in C. You may use it as a guide to finish your project.
#include "stdio.h" void towers(int,char,char,char); void towers(int n,char frompeg,char topeg,char auxpeg) { /* If only 1 disk, make the move and return */ I f(n==1) printf("\nMove disk 1 from peg %c to peg %c",frompeg,topeg); return; } /* Move top n-1 disks from A to B, using C as auxiliary */ towers(n-1,frompeg,auxpeg,topeg); /* Move remaining disks from A to C */ printf("\nMove disk %d from peg %c to peg %c",n,frompeg,topeg); /* Move n-1 disks from B to C using A as auxiliary */ towers(n-1,auxpeg,topeg,frompeg);
The main program main() { int n; printf("Enter the number of disks : "); scanf("%d",&n); printf("The Tower of Hanoi involves the moves :\n\n"); towers(n,'A','C','B'); return 0; }
Good Luck