Written by Sai Sameera Thota on October 2, 2013 in Java > Programming

Java program to print a Pascal Triangle

GET ALERTS:

Get our Latest updates delivered to your mailbox!

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

{ 2 comments… read them below or add one }

Susmit Sarkar February 16, 2016 at 11:44 pm

Amazingly simple code !! It helped me a lot, thanks 🙂

Reply

Vraj Gandhi September 26, 2016 at 11:04 pm

Thank you very much, a very helpfull program.

Reply

Leave a Comment

Previous post:

Next post: