In the provided code for Pascal Triangle I would really appreciate if one could help me clear the following doubts.
1 public class Pascal {
2
3 static void calculatePascal (int[][] t) {
4 for (int i=0; i<t.length; i++) {
5 // the first entry in each row is 1
6 t[i][0] = 1;
7
8 for (int j=1; j<t[i].length-1; j++) {
9
10 t[i][j] = t[i-1][j-1] + t[i-1][j];
11 }
12 // the last entry in each row is 1
13 t[i][ t[i].length-1 ] = 1;
14 }
15 }
16
17 static void printTriangle (int[][] t) {
18 for (int i=0; i<t.length; i++) {
19 for (int j=0; j<t[i].length; j++) {
20 System.out.print( t[i][j] + " " );
21 }
22 System.out.println();
23 }
24 }
25
26 public static void main (String[] args) {
27 int lines = Integer.parseInt( args[0] );
28 int[][] triangle = new int[lines][];
29 for (int i=0; i<lines; i++) {
30 triangle[i] = new int[ i+1 ];
31 }
32 calculatePascal(triangle);
33 printTriangle(triangle);
34 }
35
36 }
What does line 30 mean? In line 28, we make a 2-dimensional array called triangle. In line 30 what is being done?
Also how to indent the Pascal triangle in triangular form in this case?
Why did we declare the return type of both the methods calculatePascal and printTriangle as void?
null
values assigned by default. In line 30 you replace each null
by new array, which size is one more than its index. triangle[0] = [1]
triangle[1] = [1, 1]
triangle[2] = [1, 2, 1]
triangle[3] = [1, 3, 3, 1]
...