1
Announcements Lecture 13
• Assignment 3
– designs due Friday to your TA at beginning of recitation
(not in lecture)
• IPO, functional block diagram, algorithm
• Exam 1 on Friday
– Study tip: work the sample exam, specific exercises in the
book (today), solutions are on BB
– Be early !!,
bring your student ID
, pencil(s),
– Bring Assn 2 data
• # statements, # hours, # logic defects
• Topics for today
– Finish recursion
– Scope of variables (Ch. 10.1-10.4)
– Exam preview
Towers of Hanoi
- 4 disc example -
A
B
C
src
aux
dst
Towers of Hanoi
- 4 disc example -
A
B
C
src
aux
dst
http://www.mazeworks.com/hanoi/index.htm
See:
Recursive Solution
• The three pegs are
A
(Source),
B
(Auxiliary),
C
(Destination).
• Sooner or later the bottom disk will have to be moved from A to C. At this
point all the remaining disks will have to be stacked in decreasing size order
on B. After moving the bottom disk from A to C the other disks will have to
be moved from B to C.
• Therefore, for a given number of N disks, the problem can be solved if we
know how to accomplish the following tasks:
1.
Move the top N-1 disks from A to B (using C as an intermediary peg)
2.
Move the bottom disk from A to C
3.
Move N-1 disks from B to C (using A as an intermediary peg)
• Create a function
Solve
with four arguments - three pegs (source, intermediary and
destination - in this order), and the number of disks. The algorithm looks like:
Solve (A, B, C, N)
if N is 1 Move disk from A to C
else
Solve (A, C, B, N-1)
Move disk from A to C
Solve (B, A, C, N-1)
• The
Solve
function is recursive in that it calls itself repeatedly with
decreasing values of N until a terminating condition (N=1) has been met.
Tower of Hanoi Program (in C)
/* This is the main driver function for the Tower of Hanoi
*/
void solve (char, char, char, int); /* prototype for solve
*/
int
main( )
{
int numDisks;
/* holds the number of disks to play with */
/* set the initial 3 pegs - A, B and C from left to right. */