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.
Of course, it would be worth while to copy this program
to a file and run it.
Copy and paste the entire program
(both classes) into the file TriangleTester.java.
This can be done because only one class is public.
Here is the output of the program:
C:\JavaSource>javac TriangleTester.java C:\JavaSource>java TriangleTester Triangle(4) is 10
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)?