Java program to print a Pascal Triangle

Pascal triangle is a triangular array of binomial coefficients. The first row of pascal triangle contains 1.
The subsequent rows are formed by adding the above left number with the above right number. We will write a Java Program to print a Pascal Triangle.

The program takes the number of rows as input and display the pascal triangle. It uses three for loops.
The first for loop is used to determine the row in which the numbers should be printed. The second for loop
is used to print the spaces in the beginning of the line and the other for loop is used to print the number.

Java program to print a Pascal Triangle

import java.io.*;
class Pascal
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("\nEnter the number of rows : ");
		int r = Integer.parseInt(br.readLine());
		for(int i=0;i<r;i++)
		{
			for(int k=r;k>i;k--)
			{
				System.out.print(" ");
			}
            int number = 1;
			for(int j=0;j<=i;j++)
			{

				 System.out.print(number+" ");
                 number = number * (i - j) / (j + 1);
				 
			}
			System.out.println();
		}

	}
}

Download Source Code

Output:
Pascal

Leave a Reply