SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Spring 2004
Prof. Doug Baldwin
Hand out Lab 4
Sections 6.2 through 6.5
Indices
Mathematically, recursion is like induction
String manipulation, e.g., myReplace
Recursions that return results, e.g., howManyDigits
Be careful about termination
Recursive algorithms
Sequences vs lists of steps
Recursons split into 3 parts
Methods with multiple recursions
Things to avoid
Make dummy methods (?)
guessRoot( n, low, high )
root( n )
root ( n ) {
guessRoot( n, 0, n )
}
downAndUp algorithm
downAndUp( n )
if n > 0
print n
downAndUp( n-1 )
print n
Count the tiles between robot's starting position (inclusive) and wall, without using a "counter" variable or parameter
public int countToWall( ) {
if ( this.okToMove() ) {
this.move();
return 1 + this.countToWall( )
}
else {
return 1;
}
}
Paint each step walked, as in lineToWall, then search room for painted squares?
Recursively compute partial answer, then build full answer and return it
Recursively search elements 0 through n of array A for a value x, returning True or False
boolean find( int x, int[] A, int n ) {
if ( n < 0 ) { // test, part 1
// base case 1
return false;
}
else if ( A[n] == x ) { // test, part 2
// base case 2
return true;
}
else {
// recursive case
return find( x, A, n-1 );
}
}
Print a balanced string of n pairs of parentheses
void parens( int n ) {
if ( n > 0 ) {
print "("
parens( n-1 )
print ")"
}
}
Print the balanced parentheses, but put a "*" in the center
void parensAndStar( int n ) {
if ( n > 0 ) {
print "("
parensAndStar( n-1 )
print ")"
}
else {
print "*"
}
}
Print an unbalanced string of parentheses, n "(" followed by 2n ")"
void unbalancedParens( int n ) {
...
}