Java program to display pascal triangle

Let’s learn java program to display pascal triangle.

Java program to display pascal triangle

Pascal’s triangle is a triangle of binomial coefficients arranged in the form of a triangle. Pascal’s triangle is named after french mathematician Blaise Pascal. Pascal’s triangle looks like this,

java program to display pascal triangle

In the above pascal’s triangle there are five rows. First row starts with digit 1. Then each digit in a row is the sum of left digit and right digit of above row. Suppose, if a digit is missing in the above row, it is assumed as 0.

NOTE:

  • diagonals adjacent to the border diagonals contain natural numbers in an order.
  • sum of numbers in each row is twice the sum of numbers in above row.

Binomial coefficient can be calculated using formula,

C(n,r) = n!/((n-r)!*r!)

Time complexity: O(n²) where n is number of lines.

Here’s the java program to display pascal triangle.

import java.util.Scanner;
public class PascalsTriangleJava 
{
   static int findFactorial(int number)
   {
      int factorial;
      for(factorial = 1; number > 1; number--)
      {
         factorial *= number;
      }
      return factorial;
   }
   // here's the function to display pascal's triangle
   static int printPascalTraingle(int num, int p) 
   {
      return findFactorial(num) / (findFactorial(num - p) * findFactorial(p));
   }
   public static void main(String[] args) 
   {
      int row, a, b;
      System.out.println("Please enter number of rows: ");
      Scanner sc = new Scanner(System.in);
      row = sc.nextInt();
      System.out.println("Here's is pascal's triangle: ");
      for(a = 0; a < row; a++) 
      {
         for(b = 0; b < row - a; b++)
         {
            System.out.print(" ");
         }
         for(b = 0; b <= a; b++)
         {
            System.out.print(" " + printPascalTraingle(a, b));
         }
         System.out.println();
      }
      sc.close();
   }
}


Output:

Please enter number of rows: 6
Here’s is pascal’s triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Please enter number of rows: 9
Here’s is pascal’s triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1


Also read – TreeMap in java