Java Program to Print Pascal’s Triangle

You are currently viewing Java Program to Print Pascal’s Triangle

Java program to print Pascal’s triangle

import java.util.Scanner;

public class Pattern13
{
	public static void main(String[] args) 
	{
		// initialize variables.
		int lib,p,q,r,x;

		// create object of scanner.
		Scanner s=new Scanner(System.in);

		// enter number of rows.
		System.out.print("Enter the rows : ");
		r=s.nextInt();
		lib=1;  
		q=0;

		// here the pascals triangle.
		System.out.println("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))
					lib=1;
				else
					lib=(lib*(q-x+1))/x;
				System.out.print("      ");
				System.out.print(lib);
			}
			System.out.println("");
			++q;
		}
	}
}

Output

Enter the rows : 10
Pascal's Triangle :
                                              1
                                           1      1
                                        1      2      1
                                     1      3      3      1
                                  1      4      6      4      1
                               1      5      10      10      5      1
                            1      6      15      20      15      6      1
                         1      7      21      35      35      21      7      1
                      1      8      28      56      70      56      28      8      1
                   1      9      36      84      126      126      84      36      9  

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply