Java program to display pascal triangle

In this post we are going to learn java program to display pascal triangle.

java program to display pascal triangle

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

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

In the above 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.

Pascal’s triangle logic

Pascal triangle will print numbers according to particular order. Here printing numbers depends on number of rows as an input.

Suppose, if you take five rows as an output for pascal triangle it looks like above figure.

First row of pascal’s triangle starts with 1. Then in second row we have 1 and 1. So it starts with 1 it ends with 1.

And then in third row there are three numbers, it starts with one and ends with one.

But middle number is the sum of 1 + 1 in the second row (see above figure). Now in the fourth row there should be 4 numbers.

Again it starts with 1 and ends with 1, then the middle two numbers will be the sum of 1 + 2 and 2 + 1 that is 3 and 3 of previous row(see above figure).

Finally in the last row, again, it starts with 1 and ends with 1. In between it will be the sum of 1 + 3, 3 + 3 and 3 + 1, that is 4, 6 and 4.

So unlike floyd’s triangle we are not incrementing the number. Everytime we are printing a number which is first initialized to 1.

Here’s the java program to display pascal triangle,

import java.util.Scanner;

public class PascalsTriangle 
{
   public static void main(String[] args) 
   {
      System.out.println("Please enter number of rows : ");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();
      int row = num;
      int number = 1; 
 
      for(int i = 0; i < num; i++)
      {
         for(int r = 1; r <= row; r++)
         {
            System.out.print(" ");
         }
         number = 1;
         for(int j = 0; j <= i; j++)
         {
            System.out.print(number + " ");
            number = number * (i - j) / (j + 1); 
         }
         row--;
         System.out.println();
         sc.close();
      }
   }
}

Output:

java program to display pascal triangle

Related Posts