public class PascalTriangle {
public static void main(String[] args) {
showPascal(9);
}
// This takes O(n^2) constraint.
public static void showPascal(int rows){
// rows = Number of Pascal triangle rows to show up
// i = loop thru each row.
for(int i = 0; i<rows; i++)
{
// Start from 1. So, initialize the first number to 1
int number = 1;
// Give the spacing - Ex: If rows is 9, then the spacing would 18 (because I specified the args as "", else if I specify args as "_", you would notice that the spacing is 17 and on 18th bit there would be a '_' ) for the first iteration of i = 0.
System.out.format("%"+(rows-i)*2+"s", "");
// j = loop thru each column of a row by CALCULATing and display
for(int j=0; j<=i; j++)
{
// Give 3 more spacing and print the number on the 4th bit.
System.out.format("%4d", number);
// Formula to calculate each column.
number = number * (i - j)/(j + 1);
}
// Print a empty line after each row.
System.out.println();
}
}

Here is how the output look like:

Happy Coding !!!

### Like this:

Like Loading...

*Related*