Sure. The Java code describes the computation you want done, just like the math-like definition of Triangle.
class TriangleCalc { public int Triangle( int N ) { if ( N == 1 ) return 1; else return N + Triangle( N-1 ); } } public 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:\JavaSource>java TriangleTester Triangle(4) is 10
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
.
There is a formula that gives the value of
Triangle(N)
in one step.
But let us continue with the recursive definition.
What is Triangle(500)
?