Java Reference
In-Depth Information
We can turn this into actual code by using the appropriate array indexes:
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
We need to include this statement in a for loop so that it assigns all of the middle
values. The for loop is the final step in converting our pseudocode into actual code:
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
If we include this code in a method along with a printing method similar to the grid-
printing method described earlier, we end up with the following complete program:
1 // This program constructs a jagged two-dimensional array
2 // that stores Pascal's Triangle. It takes advantage of the
3 // fact that each value other than the 1s that appear at the
4 // beginning and end of each row is the sum of two values
5 // from the previous row.
6
7 public class PascalsTriangle {
8 public static void main(String[] args) {
9
int [][] triangle = new int [11][];
10
fillIn(triangle);
11
print(triangle);
12 }
13
14 public static void fillIn( int [][] triangle) {
15 for ( int i = 0; i < triangle.length; i++) {
16 triangle[i] = new int [i + 1];
17 triangle[i][0] = 1;
18 triangle[i][i] = 1;
19 for ( int j = 1; j < i; j++) {
20 triangle[i][j] = triangle[i - 1][j - 1]
21 + triangle[i - 1][j];
22
}
23
}
24 }
25
Search WWH ::




Custom Search