SUNY Geneseo Department of Computer Science


Recursion, Part 2

{Date}

CSci 141, Spring 2004
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Misc

Hand out Lab 4

Questions?

Recursion

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

Mini-Assignment

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

More Recursion Examples

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 );
        }
    }

[Array Section as Smaller Section and Single Item]

Print a balanced string of n pairs of parentheses

    void parens( int n ) {
        if ( n > 0 ) {
            print "("
            parens( n-1 )
            print ")"
        }
    }

[A Copy of a Method and the Net Result]

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 ) {
        ...
    }

Next Lecture