Skip to main content

CIS 163

Recursion, part 2

Summer 2020

Objectives:

Activity

You are strongly encouraged to work with a partner.

Create and clone this GitHub Classroom repository: classroom.github.com/g/rphpwuLZ

  1. Determine the output of the following program. (Without typing it in and running it! There is a good chance you will have a similar "tracing" problem on the final. Practice solving it "by hand.")
    public class Recursive1 {
    	private int counter = 0;
    	
    	public int stuff (int x, int y) {
    		counter++;
    		if (x < 1 || (y < 1))
    			return 1;
    		return x + y + stuff (x - 1, y - 2);
    		
    	}
    
    	public static void main (String[] arg) {
    		recursive1 x = new recursive1 ();
    		System.out.println("Answer = " + x.stuff(3, 3) + " Counter = " + x.counter);
    		System.out.println("Answer = " + x.stuff(6, 6) + " Counter = " + x.counter);
      }	
    }
    
  2. Write a recursive method to compare two strings: int compareTo(String s1, String s2). Remember, that compareTo returns
    • a negative number if s1 < s2,
    • 0 if s1 == s2, and
    • a positive number if s1 > s2.
  3. Modify (if necessary) your previous implementation so that it does not repeatedly copy part of the Strings. (Hint: Use the "start" trick we used for arrays.)
  4. Write a recursive method int parseInt(String s) that returns the integer represented by s. Throw a NumberFormatException if s does not contain an integer.
  5. Write recursive code to draw a fractal. One option is to use the starter code provided and draw the Koch Snowflake. (See mathworld.wolfram.com/KochSnowflake.html) The starter code contains the math/trigonometry for finding the different points on the line. Another fun option is to draw the Sierpinski Triangle. (See en.wikipedia.org/wiki/Sierpi%C5%84ski_triangle)

Submission

Put all your solutions into the repository and commit. If you worked with a partner, be sure both names are in a comment at the head of each file.

Updated Monday, 15 June 2020, 7:47 PM

W3c Validation