Pascal’s Triangle in Java

Pascal’s Triangle is a triangular array of numbers in which the ends of the rows are 1s and the rest are the sum of the nearest two numbers in the row above.

Below is an example of this pattern:

Pascal’s Triangle Example

Below is the source code in Java to display the Pascal’s Triangle for the first ‘n’ rows:

import java.io.*;
class PascalsTriangle{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Number of rows: ");
        int n = Integer.parseInt(br.readLine());
        for(int i = 0; i < n; i++){
            for(int j = 0; j <= i; j++){
                long t = fact(i) / (fact(i - j) * fact(j));
                System.out.print(t);
            }
            System.out.println();
        }
    }
    public static long fact(int n){
        long f = 1L;
        for(int i = 1; i <= n; i++)
            f *= i;
        return f;
    }
}

The formula factorial(line number) / (factorial(line – ith term in that line) * factorial(ith term in that line)) is used to generate each term for the Pascal’s Triangle.

Here, the first line is considered to be 0th line, and the first term is considered to be the 0th term.

Leave a Reply