Pyramid Program

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:

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

Pyramid Program

Here is a complete program that computes Pyramidal numbers. The user specifies N, the number of balls in a side of the base, in the command line.

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

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

public class PyramidTester
{
  public static void main ( String[] args)
  {
    int argument = Integer.parseInt( args[0] ); // Get argument from the command line

    Calculate calc = new Calculate();
    int result = calc.Pyramid( argument );
    System.out.println("Pyramid(" + argument + ") is " + result );
  }
}

The program must include a method for Triangle(). Here is a run of the program:

C:/>java PyramidTester 12
Pyramid(12) is 364

QUESTION 6:

Could the program (above) use an iterative method for Triangle() and a recursive method for Pyramid()?