CS111 PreLab 6

This prelab introduces you to using and understanding recursion, both by drawing a recursive JEM, and by writing a recursive method.

Task 1a

Results of asking tara to throw bagels at distances of 0,1,2,3,4 and 5:

Task 1b

JEM for invocation of TW1.run() :

 

Task 2

To solve the problem, follow the steps for solving a problem recursively:

Analyze the pattern: The triangle is formed from rows of painted cells, with bagels dropped at each end of the rows. Each row is 2 shorter in length than the next lower row.

Base case: When size = 0 or 1,nothing is drawn

if (size <= 1) {

// base case, do nothing

}

What is done in a single recursion layer: At each level of recursion, a new row of length (size + 1) is drawn, with a bagel dropped at each end. The starting and ending position is in the middle of the row, facing NORTH:

drawRow(size); //auxiliary method

How to move to the next recursion layer: Simply move up one square to the next row:

forward();

How to make the next recursive call: Invoke the recursive method with size - 1:

triangle(size - 1);

Meet invariant (if there is one): None in this problem (the buggle is not required to return to it's original position).

 

The following TriBuggle class contains methods which draw the triangle recursively:

class TriBuggle extends Buggle {

public void triangle(int size) {

if (size <= 1) {

// base case, do nothing

} else {

drawRow(size);

forward();

triangle(size - 1);

}

}

//draws a row of length size+1, with a bagel at each end

public void drawRow(int size) {

right();

backward(size - 1);

dropBagel();

forward(2 * (size - 1));

dropBagel();

backward(size - 1);

left();

}

 

p