Pascal Triangle

Generate Pascal’s triangle using loops and binomial coefficients.

JavaIntermediate
Java
public class Main {
    private static int nCr(int n, int r) {
        int res = 1;
        for (int i = 0; i < r; i++) {
            res = res * (n - i) / (i + 1);
        }
        return res;
    }

    public static void main(String[] args) {
        int rows = 5;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(nCr(i, j) + " ");
            }
            System.out.println();
        }
    }
}

Output

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

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