Program to Print Pascal Triangle in Java

Pascal’s triangle is a set of numbers arranged in the form of a triangle. Each number in a row is the sum of the left number and right number on the above row. If a number is missing in the above row, it is assumed to be 0. The first row starts with number 1. The following is a Pascal triangle with 5 rows,

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

The triangle is named after the French mathematician Blaise Pascal who organized detailed information on the triangle in a book. However this triangle was known in many ancient civilizations.

Pascal’s triangle has a number of unique properties,

  • The sum of numbers in each row is twice the sum of numbers in the above row
  • The diagonals adjacent to the border diagonals contains natural numbers in order

Generate Pascal’s Triangle in Java

The following Java program prints Pascal’s triangle with 10 rows.

/* Program to print pascal triangle for 10 rows in java */
public class PascalTriangle {
    
    public static void main(String[] args) {
        
        int rows = 10;
        
        
        for(int i =0;i<rows;i++) {
            int number = 1;
            System.out.format("%"+(rows-i)*2+"s","");
            for(int j=0;j<=i;j++) {
                 System.out.format("%4d",number);
                 number = number * (i - j) / (j + 1);
                
            }
            System.out.println();
        }
        
    }
}

Note the formatting commands used above to create a nicely formatted triangle. %4d instructs the formatter to print the number within 4 spaces. We choose 4 since we know the maximum number of digits in the largest number of a Pascal triangle with 10 rows is 3 digits.

The following program prints a Pascal’s triangle when the number of rows are given as a parameter,

/* Program to print pascal triangle for 10 rows in java */
public class PascalTriangle {
    
    public static void main(String[] args) {
        
        int rows = Integer.parseInt(args[0]);
        
        
        for(int i =0;i<rows;i++) {
            int number = 1;
            System.out.format("%"+(rows-i)*2+"s","");
            for(int j=0;j<=i;j++) {
                 System.out.format("%4d",number);
                 number = number * (i - j) / (j + 1);
                
            }
            System.out.println();
        }
        
    }
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply