Pascal's Triangle (First 5 Rows)

This program prints Pascal's Triangle.

Problem Statement

Write a Java program that prints Pascal's Triangle with 5 rows.

Source Code

1 public class PascalsTriangle {
2 public static void main(String[] args) {
3 int rows = 5;
4 for(int i=0; i<rows; i++) {
5 int num = 1;
6 for(int j=0; j<=i; j++) {
7 System.out.print(num + " ");
8 num = num * (i - j) / (j + 1);
9 }
10 System.out.println();
11 }
12 }
13 }

Program Output

1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 

Explanation

Each row starts with num=1, and the inner loop computes each subsequent binomial coefficient using the formula num = num * (i - j) / (j + 1), so rows form Pascal's Triangle demonstrating mathematical pattern generation using nested loops.

Quick Links to Explore