Hello everyone..!! Welcome to flower brackets blog. In this post we are going to learn pascal’s triangle java.

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 a particular order. So printing numbers always depends on number of lines as an input.

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

In the first line it starts with 1. But in floyd’s triangle it starts with 2 and then 3. But in pascal triangle every line it starts with 1.

Then in second line we have 1 and 1. So it starts with 1 it ends with 1. And then in the third line 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 (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 lines : "); 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:**

Please enter number of lines : 4

1

1 1

1 2 1

1 3 3 1