
/** 
 A class to build up rows of numbers to form Pascal's Triangle
 */
public class PascalTriangle {
  
  private int[][] tr;
  
  /**
   Initializes an instance Pascal's Triangle with the specified number
   of rows.
   @param n number of rows to generate
   */
  public PascalTriangle( int n ) {
    tr = new int[n][];
    for ( int row = 0; row < n; row++ ) {
      // allocate space for this row
      tr[row] = new int[row+1];
      // set first and last elements to 1
      tr[row][0] = 1;
      tr[row][row] = 1;
      // compute internal elements
      for ( int col = 1; col < row; col++ ) 
        tr[row][col] = tr[row-1][col-1] + tr[row-1][col];
    }
  }
  
  
  /**
   Returns a string representation of Pascal's Triangle
   */
  public String toString() {
    String s = new String();
    for ( int row = 0; row < tr.length; row++ ) {
      for ( int col = 0; col < 2 * (tr.length - row - 1); col++ ) 
        s += ' ';
      for ( int col = 0; col < tr[row].length; col++ )
        s += tr[row][col] + "  ";
      s += '\n';
    }
    return s;
  }
  
  
  /**
   Computes the sum of all the numbers in the Pascal Triangle
   @return sum of number in the Triangle
   */
  public int sum() {
    int sum = 0;
    for ( int row = 0; row < tr.length; row++ )
      for ( int col = 0; col < tr[row].length; col++ )
        sum += tr[row][col];
    return sum;
  }
  
  
  public static void main( String[] args ) {
    PascalTriangle p1 = new PascalTriangle( 5 );
    PascalTriangle p2 = new PascalTriangle( 1 );
    PascalTriangle p3 = new PascalTriangle( 20 );
    
    System.out.println( p1 );
    System.out.println( p2 );
    System.out.println( p3 );
    
    System.out.println( "Sum of third triangle elements: " + p3.sum() );
  }
  
}