Java Code for Printing Pascal Triangle in Format

The following java code accepts the number of rows the Pascal triangle to be printed. Then it prints the Pascal Triangle in the Format.

package com.javaonline;

import java.io.*;

public class PascalTriangle {

public static void main(String args[]) {

try{

System.out.println("Enter No of Rows Pascal pt to be printed");

BufferedReader br=new BufferedReader (new InputStreamReader (System.in));

int rows = Integer.parseInt(br.readLine());

int pt[][] = new int[rows][rows];

// to initialize the arrays

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

{

	for (int j = 0; j <= i; j++)

		{

			pt[i][j] = 0;

		}

}

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

	{

		for (int j = 0; j <=i; j++)

			{

				if(j==0)

					{

						pt[i][j] = 1;

					}

				else

					{

						pt[i][j] = pt[i-1][j-1] + pt[i-1][j];

					}			

			}

	}

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

		{

			for(int s=rows-i ; s>=0 ;s--)

				{

					System.out.print(" ");

				}

			for(int j=0;j<=i;j++)

				{

					System.out.print(pt[i][j] +" " );

				}

			System.out.println();

		}

	}

catch (Exception e)

{

System.out.println("Error");

}

}

}

Running the above program :

pascal triangle

You may also like

Leave a Reply