Two Parts to Recursion

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

The new method does not test for a base case.

Two Parts to Recursion

I can't allow a chapter to go by without reminding you of this: A recursive definition has two parts:

  1. If the problem is easy, solve it immediately.
  2. If the problem can't be solved immediately, divide it into smaller problems, then:
    • Solve the smaller problems by applying this procedure to each of them.

Our seriously wrong drawStar() method does not test for a base case. Look at it again:

 
  // Seriously Wrong Method
  //
  private void drawStar( int x, int y, int size )
  {
    int endX, endY ;
     
    // Six lines radiating from (x,y)
    for ( int i = 0; i<6; i++ )
    {
      endX = x + (int)(size*Math.cos( (2*Math.PI/6)*i ));
      endY = y - (int)(size*Math.sin( (2*Math.PI/6)*i ));
      graph.drawLine( x, y, endX, endY );
      drawStar( endX, endY, size/3 ) ;
    }
  }

Everytime it is called, it calls itself again. It does not test for a case where it can return to its caller.

QUESTION 12:

(You might want to think about this: ) What base case should this method test for?