go to previous page   go to home page   go to next page

Answer:

The new method does not test for a base case.


Two Parts to Recursion

 
  // Seriously Wrong Method
  //
  private void drawStar( Graphics gr, 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 )  // draw star at end of line ;
    }
  }

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 (the easy problem). Everytime it is called, it calls itself again. It does not have a case where it can return to its caller and so will go on forever.


QUESTION 12:

(You might want to think about this: ) What should be the base case?