-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascalTriangle.java
More file actions
34 lines (28 loc) · 1.04 KB
/
pascalTriangle.java
File metadata and controls
34 lines (28 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Question: Given an integer 'numRows'. Generate Pascal's Triangle. (using 2d arraylist);
package twoDArray;
import java.util.*;
public class pascalTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<List<Integer>> ans = new ArrayList<>();
System.out.print("Enter the number of rows: ");
int numRows = sc.nextInt();
for (int i = 0; i < numRows; i++) {
List<Integer> l = new ArrayList<>();
for (int j = 0; j <= i; j++) {
// First and last element in each row is 1
if (j == 0 || j == i) {
l.add(1);
} else {
// Middle elements are sum of two elements above
l.add(ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));
}
}
ans.add(l);
}
// Print Pascal's Triangle
for (List<Integer> ele : ans) {
System.out.println(ele);
}
}
}