Extension 3.1: Pascal’s Triangle (4 points)

Authors

Take a look at the Wikipedia page on Pascal's Triangle. We will implement this using a two-dimensional array, so it may be easier to imagine the entries left-justified rather than in triangular form:

        column
        0  1  2  3  4
row
0       1
1       1  1
2       1  2  1
3       1  3  3  1
4       1  4  6  4  1
                .
                .
                .

Viewed as a two-dimensional array, the computation is specified as follows, for each entry at row r and column c :

Procedure

  1. Open the PascalsTriangle class, found in the arrays package of the extensions folder.

  2. Insert code to obtain from the user the value N which is the number of rows you should compute of the triangle.

  3. Instantiate the two-dimensional array needed to hold the results.

    Java lets you do this as a ragged array, where each row can be of a different length.

    You are welcome to instantiate the array that way, but it is simpler and equally acceptable to instantiate the array with the same number of columns in each row.

  4. Fill in the 2D array with the values of the triangle.

  5. Print the results left-justified as shown above. The columns must be aligned up to row 12. You may use any approach to aligning the columns, but we recommend using tabs (\t).

You have attempted of activities on this page