Java Reference
In-Depth Information
1 + 2 + ș + n = n ¶ ( n + 1) / 2
Thus, the area equals
width * (width + 1) / 2
Therefore, neither recursion nor a loop is required to solve this problem. The
recursive solution is intended as a Ȓwarm-upȓ to introduce you to the concept of
recursion.
ch13/triangle/Triangle.java
1 /**
2 A triangular shape composed of stacked unit squares like this:
3 []
4 [][]
5 [][][]
6 È
7 */
8 public class Triangle
9 {
10 /**
11 Constructs a triangular shape.
12 @param aWidth the width (and height) of the triangle
13 */
14 public Triangle( int aWidth)
15 {
16 width = aWidth;
17 }
18
19 /**
20 Computes the area of the triangle.
21 @return the area
22 */
23 public int getArea()
24 {
25 if (width <= 0 ) return 0 ;
26 if (width == 1 ) return 1 ;
27 Triangle smallerTriangle = new
Triangle(width - 1 );
590
591
Search WWH ::




Custom Search