Pascal Triangle in Java

Generate Pascal’s triangle using loops and binomial coefficients.

IntermediateModule 3: Loop ProgramsExample 18 of 25
pascal-triangle.java
1public class Main {
2 private static int nCr(int n, int r) {
3 int res = 1;
4 for (int i = 0; i < r; i++) {
5 res = res * (n - i) / (i + 1);
6 }
7 return res;
8 }
9
10 public static void main(String[] args) {
11 int rows = 5;
12 for (int i = 0; i < rows; i++) {
13 for (int j = 0; j <= i; j++) {
14 System.out.print(nCr(i, j) + " ");
15 }
16 System.out.println();
17 }
18 }
19}

Output

1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1

What's going on

We use a small helper to compute nCr iteratively and print rows of Pascal’s triangle.