Java Method

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

Yes. The calculation gets rather tedious, but the definition works for all positive integers.

Java Method

It might be nice to have a Java method that does the calculation for us. Here is a math-like definition of Triangle(N):

  1. Triangle( 1 ) = 1
  2. Triangle( N ) = N + Triangle( N-1 )

And here is a Java method that does this calculation:

int Triangle( int N )
{
  if ( N == 1 )
    return 1;
  else
    return N + Triangle( N-1 );
}

The Java code is similar to the math-like definition of Triangle(). The if statement has been added so that the base case is selected when it is needed.

QUESTION 8:

Is it OK to have Triangle( N-1 ) in the body of the method?