In this blog post, we’ll learn how to print Pascal’s Triangle using Java. It’s a famous triangle of numbers that represents binomial coefficients, and it's also asked frequently in interviews.
π What is Pascal’s Triangle?
Pascal’s Triangle is a triangle where each number is the sum of the two numbers directly above it. The triangle starts with a 1 at the top, and the edges are always 1.
Example for n = 5 rows:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
✅ Java Program to Print Pascal’s Triangle
public class PascalsTriangle {
public static void main(String[] args) {
int rows = 5;
for (int i = 0; i < rows; i++) {
// Print leading spaces
for (int space = 1; space < rows - i; space++) {
System.out.print(" ");
}
int number = 1;
for (int j = 0; j <= i; j++) {
System.out.print(number + " ");
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
π§ Interview Tip
Pascal’s Triangle tests your understanding of loops, math (combinations), and printing with proper formatting. The formula used is based on: nCr = n! / (r!(n - r)!)
but is optimized using iteration.
π― Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
π Conclusion
We have seen how to print Pascal’s Triangle in Java. This is not only a popular pattern program but also builds your understanding of nested loops and combinatorial math.