SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Spring 2005
Prof. Doug Baldwin
Hand out Lab 4
Ways to make sure recursion terminates
Three parts
Inversion
Don't do recursion before test
Recursive algorithm to print n 1's followed by n 2's
print12( n )
if n > 0
print 1
print12( n-1 )
print 2
else
Print n 1's followed by 2n 2's
print1Double2( n )
if n > 0
print 1
print1Double2( n-1 )
print 2
print 2
else
do nothing
Use the robot to draw a "bracket" n tiles on a side, n >= 1
// In some subclass of Robot...
bracket( n )
if n > 1
this.paint(Yellow)
this.move()
this.bracket( n-1 )
this.move()
this.paint( Yellow )
else
this.paint( Yellow )
this.turnLeft()
Some final discussion of the "bracket" algorithm
How do you know a recursive algorithm is really correct?