Base Case

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:

It activates Triangle() with a parameter of 1.

Base Case

Four Activations

Finally we are at the base case. When Triangle() is activated with a parameter of 1, the if statement causes the value 1 to be immediately returned.

The chain of activations is called an activation chain. The picture on this page shows the activation chain when it has reached the base case.

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

Now look again at the activation where N = 2. It has just gotten a value back from Triangle(1):


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

QUESTION 14:

What value does this activation return to its caller?