Patterns
Java Program to Print Pascal's Triangle
A Java program to print Pascal's Triangle.
Problem Description
Write a Java program to print Pascal's Triangle.
Code
public class PascalsTriangle {
public static void main(String[] args) {
int rows = 5, coef = 1;
for(int i = 0; i < rows; i++) {
for(int space = 1; space < rows - i; ++space) {
System.out.print(" ");
}
for(int j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
System.out.printf("%4d", coef);
}
System.out.println();
}
}
}Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1Explanation
- Formula:
C(n, k) = C(n, k-1) * (n - k + 1) / k. - Formatting: Use
printffor proper spacing.
