1
2 PROGRAM towers_of_hanoi;
3
4 {This program solves a well known game using recursive procedures calls
5 and user defined data}
6
7 TYPE poles=(left,centre,right);
8 disks=0..maxint;
9
10 VAR n:disks;
11
12 PROCEDURE transfer(n:disks;origin,destination,other:poles);
13
14 {Note that origin,destination and other are formal parameters for the
15 procedure transfer,they are supposed to be replaced by the actual parameter
16 left,centre,right in the procedure reference in the main program}
17
18 {Transfer n disks from the origin to the destination}
19
20 PROCEDURE diskmove(origin,destination:poles);
21
22 {Move a single disk from the origin to the destination}
23 BEGIN
24 write('Move ');
25 CASE origin OF
26 left :IF destination=centre
27 THEN writeln('left to centre')
28 ELSE writeln('left to right');
29 centre :IF destination=left
30 THEN writeln('centre to left')
31 ELSE writeln('centre to right');
32 right :IF destination=centre
33 THEN writeln('right to centre')
34 ELSE writeln('right to left');
35 END; {End case}
36 END; {End diskmove}
37 BEGIN {Transfer}
38 IF n>0 THEN BEGIN
39 transfer(n-1,origin,other,destination);
40 diskmove(origin,destination);
41 transfer(n-1,other,destination,origin);
42 END;
43 END; {End Transfer}
44
45 BEGIN {Main action block}
46 write('Enter the number of disks->');
47 readln(n);
48 writeln;
49 transfer(n,left,right,centre); {Transfer n disk from left to right}
50 END.
51
52
53
54