Java program to print pascal triangle - Java coding

Pascal triangle is a triangle with numbers in different positions as shown in the image here. Here is the java program to take the number from user and print Pascal triangle.

Pascal triangle is a triangle with numbers in different positions as shown in the image below. Pascal triangle has the number positioned in the form of a triangle. The number in a row is the sum of the left and right number on the row above it. If no number is on the left or right the number is taken as zero. The row starts with one. So if you choose any number from the triangle shown below and add the numbers just above it in left and right positions respectively, then you will get back the same number which you have chosen.

Now let us see a program to print this pascal triangle in java programming language. You just need to know the logic behind this program and then you can rewrite this program in any other language you want.

## Program to print Pascal triangle in Java

The Program to print Pascal triangle in java is shown below. It will print the pascal triangle up to 10 rows. The program is very straight forward. The logic behind this pascal triangle is simple. We have created a for loop from 0 to 9. %4d is used to print the number within the four spaces. Four is chosen because the max no of digits in the largest number of a Pascal triangle with 10 rows is 3 digits.

The below program is a simpler version of the pascal triangle in java.

public class Printpascal{
public static void main(String[] args) {
int rows = 10;
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}

Now the next program will take a number from the user and print the pascal triangle.

import java.util.Scanner;
class Pascaltriangle
{
public static void main(String[] args)
{
int bin,p,q,r,x;
Scanner s=new Scanner(System.in);
System.out.println("How Many Row Do you want to input: ");
r=s.nextInt();
bin=1;
q=0;
System.out.print("Pascal's Triangle: ");
while(q<r)
{
for(p=40-3*q;p>0;--p)
System.out.print(" ");
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
bin=1;
else
bin=(bin*(q-x+1))/x;
System.out.print("      ");
System.out.print(bin);
}
System.out.println("");
++q;
}
}
}
Now to compile the program open CMD and type javac Pascaltriangle.java and to run the program type java Pascaltriangle. Here is the output of the above program.

Thank you for reading this post. Comment below for any suggestions.

Name

ltr
item
MindxMaster: Java program to print pascal triangle - Java coding
Java program to print pascal triangle - Java coding
Pascal triangle is a triangle with numbers in different positions as shown in the image here. Here is the java program to take the number from user and print Pascal triangle.