SUNY Geneseo Department of Computer Science


Introduction to Recursion

{Date}

CSci 141, Spring 2004
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

Recursion = replacing "while" with "if"?

Recursion = defining something in terms of a smaller version of itself

Introduction to Recursion

Section 6.1

Recursion

Definition (see above)

    to sing 99 bottles of beer song
        sing verse for some number
        sing song for next smaller number
    unless number is 0, in which case
        sing different verse

Lots of examples

    take one step
    take all remaining steps

Recursion in code

    if ( ... some condition ... )
        call yourself (repetition)
    else
        finish, do something simple

Sophisticated uses

The Towers of Hanoi

A relatively sophisticated use of recursion, a preview of where recursion can get you.

Goal: Move an n-disk tower from one pole to another.

Rules:

See if you can...

The puzzle can actually be Solved in 4 lines of Java, using 2 recursions.

Recursion Examples

Draw a red line from the robot's current position to a wall.

    public void lineToWall() {
        this.paint( Color.red );
        if ( this.okToMove() ) {
            this.move();
            this.lineToWall();
        }
    }

Count the tiles between robot's starting position (inclusive) and wall

[Third Tile from Wall Generates Count of 3]

    public int countToWall( int count ) {
        if ( this.okToMove() ) {
            count = count + 1;
            this.move();
            this.countToWall( count );
        }
        return count;
    }
        Robot r = new Robot();
        r.countToWall( 1 );

Next

More Recursion

Mini-assignment: countToWall with no "count" parameter, variable, etc

Read Sections 6.2 through 6.5


Next Lecture