Sure. The Java code describes the computation you want done, just like the math-like definition of Triangle.
class TriangleCalc { int Triangle( int N ) { if ( N == 1 ) return 1; else return N + Triangle( N-1 ); } } class TriangleTester { public static void main ( String[] args) { TriangleCalc tri = new TriangleCalc(); int result = tri.Triangle( 4 ); System.out.println("Triangle(4) is " + result ); } }
The above program tests this method. The value for N is hard-coded. Here is the output of the program:
C:\>java TriangleTester Triangle(4) is 10 C:\>
Of course, it would be worth while to copy this program
to a file and run it.
You might wish to
improve the program so that N is entered by the user.
If you do, have main()
test that N
is positive before it calls Triangle
.
What is Triangle(500)
?