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

Answer:

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

Pyramid Program

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 );
  }
}

Here is a complete program that computes Pyramidal numbers. The program includes Triangle().

The user specifies N, the number of balls in a side of the base, in the command line. Here is a run of the program:

C:\JavaCode>java PyramidTester 12
Pyramid(12) is 364

QUESTION 6:

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


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