Java program to print Pascal triangle

Java program to print Pascal triangle

Write a Java program to print Pascal triangle is one of the frequently asked Java coding interview questions. The question tests the candidate’s ability to write logic and the knowledge of using nested for loops.

Pascal triangle

Pascal’s triangle is a set of numbers arranged in the form of a triangle. Let us understand it better with the help of a diagram. Below is the pattern of pascal’s triangle.

java pascals triangle

Following are the characteristics of Pascal’s triangle

  • The number of elements in a row is equal to the rowth number i.e. first row contains one element, second row contains two elements, third row contains three elements and so on.
  • Each row of a Pascal’s Triangle can be calculated from the previous row. Each row begins and ends with the number 1. The remaining numbers in a row is calculated from the sum of the left number and right number on the previous row. For example, the second element in the 3rd row is the sum of the 1st element and the 2nd element of the 2nd row. Similarly the third element in the 4th row is the sum of the 2nd element and the 3rd element of 3rd row. Similar concept applies for other elements.
  • The sum of numbers in each row is twice the sum of numbers in the previous row.
  • The diagonals adjacent to the border diagonals contains natural numbers in order.

Now lets see the Java program to print pascal triangle.

Java program to print pascal triangle using recursion

This problem can also be solved using recursion since calculating the value of a particular element in the triangle depends on the previously calculated values.

The number at position row i and column j can be represented as pascal(i,j) with i and j starting from 0. The first and last element in a row is always 1 hence we can write as,

pascal ( i, 0 ) = 1
pascal ( i, i ) = 1

Following is the recursive formula used to calculate the remaining elements :

pascal ( i, j ) = pascal ( i – 1 , j -1 ) + pascal ( i – 1 , j ) // refer point 2 in the characteristics for an understanding.

Given below is the program which uses the recursion to print Pascal’s triangle.
Below is a sample output of above program.
Below Java program uses another approach to print pascal’s triangle.
Below is a sample output of running the above program.

Hope you find the post useful. For any comments, use the comments section.

Also read my another post,

Java program to print floyd’s triangle

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.