Pascal’s Triangle Java Code Example

Here is a simple Java program to print Pascal’s Triangle:

import java.util.Scanner;

public class YangHuiTriangle {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter the number of rows in Yang Hui Triangle: ");
        int numRows = input.nextInt();
        
        int[][] triangle = new int[numRows][numRows];
        
        for (int i = 0; i < numRows; i++) {
            triangle[i][0] = 1;
            triangle[i][i] = 1;
            
            for (int j = 1; j < i; j++) {
                triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
            }
        }
        
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(triangle[i][j] + " ");
            }
            System.out.println();
        }
        
        input.close();
    }
}

In this program, we first ask the user to input the number of rows for the Pascal’s Triangle to be printed. Then, we use a two-dimensional array to store the values at each position. We calculate the values at each position using two nested loops and print the entire Pascal’s Triangle.

bannerAds