Pascal Triangle

Generate Pascal’s triangle using loops and binomial coefficients.

IntermediateTopic: Module 3: Loop Programs
Back

Java Pascal Triangle Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
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

Understanding Pascal Triangle

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

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents