Pascal Triangle in Java

Here you will learn about pascal triangle in java with a program example.

What is Pascal’s Triangle?

It is a triangular array of the binomial coefficients. It is a number pattern which starts with 1 at top and then placing numbers below it in triangular pattern.

Each number is obtained by adding two numbers above it. Take below example, here 4 is obtained by adding 1 and 3 above it.

Pascal Triangle in Java
Image Source

Below I have shared the java program to print pascal triangle. Each term in the pattern is obtained by using combination formula given below.

Combination Formula

Program for Pascal Triangle in Java

package com;

import java.util.Scanner;

public class PascalTriangleJava {
	public static void main(String args[]) {
		int i,j,k,n;
		Scanner sc = new Scanner(System.in);
	
		System.out.println("How many lines?");
		n = sc.nextInt();
		
		for(i = 0; i < n; ++i) {
			//this loop will print spaces at starting of each row
			for(j = 1; j <= (n-i-1); ++j) {
				System.out.print(" ");
			}
			
			//this loop will calculate each value in a row and print it
			for(k = 0; k <= i; ++k) {
				System.out.print(fact(i)/(fact(i-k)*fact(k)) + " ");
			}
			
			System.out.print("\n");    //print new line after each row
		}
	}

	//calculate factorial
	static long fact(int x) {
		int i;
		long f = 1;
		
		for(i = 1; i <= x; ++i) {
			f = f*i;
		}
		
		return f;
	}
}

Output

Pascal Triangle in Java

Comment below if you have any doubts related to above program.

Leave a Comment

Your email address will not be published. Required fields are marked *