Recursive Programming Examples
CS2 Course Summary Slide 19

Several recursive examples involving String processing and graphics programming are presented in anticipation of an impending purely recursive linked implementation of the Linear List ADTs. These include:


Demos

os> java MysteryApp
1
2
3
4
5
os> 


os> java MysteryApp
"dad" is a palindrome
"racecar" is a palindrome
"" is a palindrome
"x" is a palindrome
"car" is not a palindrome
os> 


os> java Ring

os>

Code

public class Mystery
{
    static public void main(String args[])
    {
        mystery(5);
    }

    static private void mystery(int n)
    {
        if ( n == 0 ) { return; }
        mystery(n-1);
        System.out.println(n);
    }
}


public class PalindromeApp
{
    static public void main(String args[])
    {
        check("dad");
        check("racecar");
        check("");
        check("x");
        check("car");
    }

    static private void check(String s)
    {
        if ( palindrome(s) ) {
            System.out.println("\"" + s + "\"" + " is a palindrome");
        } else {
            System.out.println("\"" + s + "\""  + " is not a palindrome");
        }
    }

    static private boolean palindrome(String s)
    {
        if ( s.length() < 2 ) { return true; }
        String first = s.substring(0,1);
        String last = s.substring(s.length()-1);
        if ( first.equals(last) ) {
            return palindrome(s.substring(1,s.length()-1));
        } else {
            return false;
        }
    }
}


/*
 * Ring.java
 *
 * Created on June 8, 2006, 9:21 AM
 */

package testers;

import clay.canvas.ClayCanvas;
import clay.math.ClayPoint;
import clay.shapes.ClayCircle;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;

/**
 *
 * @author blue
 */
public class Ring {
    
    public static void main(String[] args) {
        RingFrame rf = new RingFrame("Ring");
        rf.setVisible(true);
        rf.canvas().initializeImage();
        ring(rf.canvas(),rf.canvas().center(),new ClayCircle(200),Color.red,Color.yellow);
     }
    
    static private void ring(ClayCanvas c,ClayPoint o, ClayCircle circle, Color c1, Color c2)
    {
        if ( circle.radius() < 10 ) { return; }
        c.paint(o,circle,c1);
        circle.shrink(10);
        ring(c,o,circle,c2,c1);
    }
        
}

class RingFrame extends Frame {
    
    private ClayCanvas canvas = new ClayCanvas();  

    public ClayCanvas canvas()
    {
        return canvas;
    }

    public RingFrame(String title)
    {
        super(title);
        setSize(500,500);
        setLayout(new GridLayout(1,1));
        add(canvas);
    }  

}