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.

Below I have shared the java program to print pascal triangle. Each term in the pattern is obtained by using combination formula given below.
Program for Pascal Triangle in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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
Comment below if you have any doubts related to above program.