Extension 3.1: Pascal’s Triangle (4 points)¶
Authors
Robert Sedgewick
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
:
If
c
is 0, then the entry is1
.If
c``==``r
, then the entry is1
.If
r
< 0 orc
< 0 orc
>r
, then the entry is0
and is not shown.Everywhere else, the entry is computed as the sum of the entries at:
r-1
,c
r-1
,c-1
Procedure¶
Open the
PascalsTriangle
class, found in thearrays
package of theextensions
folder.Insert code to obtain from the user the value N which is the number of rows you should compute of the triangle.
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.
Fill in the 2D array with the values of the triangle.
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
).