# What is Pascal’s Triangle – Java Implementation

Filed Under: Java Pascal Triangle is named after French mathematician Blaise Pascal. It is a triangular array of binomial coefficients.

The triangle follows a very simple rule.

Each number is the sum of the two numbers directly above it.

Here’s a gif that illustrates filling of a pascal triangle. By Hersfold on the English Wikipedia – Own work, Public Domain, https://commons.wikimedia.org/w/index.php?curid=3902538

The value of element (i,j) is given by C(i,j) = i!/((i-j)!*j!). Where i is the row number and j is the element position in that row.

## Java Code for Pascal’s Triangle

The Java code to print a pascal triangle is as follows.

```package com.JournalDev;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("Enter the number of rows");
int rows = s.nextInt();
int coef = 1;

for(int i = 0; i < rows; i++) {
for(int sp = 1; sp < rows - i; ++sp) {
System.out.print("  ");
}

for(int j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;

System.out.printf("%4d", coef);
}

System.out.println();
}
}
}

```

The code inputs the number of rows of pascal triangle from the user.

Let’s go over the code and understand.

## Code Breakdown

The outer most for loop is responsible for printing each row. It will run ‘row’ number of times.

``` for(int i = 0; i < rows; i++) {
```

The next for loop is responsible for printing the spaces at the beginning of each line.

``` for(int sp = 1; sp < rows - i; ++sp) {
System.out.print("  ");
}
```

We can see that as the current row number (i) increases, the number of times this loop runs will decrease.

The next for loop is responsible for printing the numbers in the triangle.

``` for(int j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;

System.out.printf("%4d", coef);
}
```

For first row and first element of each subsequent row, 1 is printed as the output.

The formula that computes the digit for the remaining positions is :

```coef = coef * (i - j + 1) / j;
```

Where i is the current row number and j is the position of the element in that row.

j is initialised to 0 for each row.

We can do a quick dry run for row number 3.

```i = 3, j = 0 -> 1 (coef)
i = 3, j = 1 -> 3 (1*(3-1+1)/1)
i = 3, j = 2 -> 3 (3*(3-2+1)/2)
i = 3, j = 3 -> 1 (3*(3-3+1)/3)
```

The row comes out to be :

```1 3 3 1
```

You should do this for row munger 4 and 5 as well to understand how the formula works.

To format the output properly, we use printf.

## Output

The output obtained after running the code is as follows :

## Conclusion

This tutorial was about pascal triangle and how to write a code for generating it. Hope you understood the concept and enjoyed learning about it!

1. Shubham Dnyaneshwar Unde says: