Java Reference
In-Depth Information
int smallerArea = smallerTriangle.getArea();
Now we can complete the getArea method:
public int getArea()
{
if (width == 1) return 1;
Triangle smallerTriangle = new Triangle(width
- 1);
int smallerArea = smallerTriangle.getArea();
return smallerArea + width;
}
A recursive computation solves a problem by using the solution of the same
problem with simpler values.
Here is an illustration of what happens when we compute the area of a triangle of
width 4.
ȗ
The getArea method makes a smaller triangle of width 3.
ȗ
It calls getArea on that triangle.
ȗ
That method makes a smaller triangle of width 2.
ȗ
It calls getArea on that triangle.
ȗ
That method makes a smaller triangle of width 1.
ȗ
It calls getArea on that triangle.
ȗ
That method returns 1.
ȗ
The method returns smallerArea + width = 1 + 2 = 3 .
ȗ
The method returns smallerArea + width = 3 + 3 = 6 .
ȗ
The method returns smallerArea + width = 6 + 4 = 10 .
This solution has one remarkable aspect. To solve the area problem for a triangle of a
given width, we use the fact that we can solve the same problem for a lesser width.
This is called a recursive solution.
Search WWH ::




Custom Search