go to previous page   go to home page   go to next page hear noise highlighting

Answer:

Yes. The calculation is 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. Assume that N is a positive integer. Here is a math-like definition of Triangle(N):

And here is a Java method that does this calculation:

public 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 detects the base case and immediately returns its value. Both the Java code and the math-like definition assume that N is positive.


QUESTION 8:

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


go to previous page   go to home page   go to next page