Generate Pascal's Triangle in Java
What you’ll learn
- How each row of Pascal’s Triangle is built from binomial-style coefficients.
- Two Java approaches: multiplicative coefficient and additive previous-row method.
- How to print rows neatly and validate row input in a live preview.
Overview
Pascal’s Triangle starts with 1, keeps 1 on both edges, and fills inner values as sums of two values above.
Prerequisites
- Java loops and nested iteration.
- Basic arithmetic and integer printing format.
The idea
Either compute each coefficient directly in a row, or build each row from the previous row’s adjacent sums.
Mini triangle intuition
Row 0: 1, Row 1: 1 1, Row 2: 1 2 1, Row 3: 1 3 3 1.
Live preview
Algorithm
For each row, print coefficients from left to right and update values using row/column relation.
📜 Pseudocode
for i from 0 to rows-1:
coeff = 1
for j from 0 to i:
print coeff
coeff = coeff * (i-j) / (j+1)Multiplicative coefficient method
public class Main {
static void generatePascalsTriangle(int rows) {
for (int i = 0; i < rows; i++) {
long coefficient = 1;
for (int s = 0; s < rows - i - 1; s++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%6d", coefficient);
coefficient = coefficient * (i - j) / (j + 1);
}
System.out.println();
}
}
public static void main(String[] args) {
generatePascalsTriangle(5);
}
}Build from previous row
public class Main {
static void generatePascalsTriangleAdditive(int rows) {
long[] prev = new long[rows];
long[] cur = new long[rows];
for (int i = 0; i < rows; i++) {
cur[0] = 1;
for (int j = 1; j < i; j++) {
cur[j] = prev[j - 1] + prev[j];
}
if (i > 0) cur[i] = 1;
for (int s = 0; s < rows - i - 1; s++) System.out.print(" ");
for (int j = 0; j <= i; j++) System.out.printf("%6d", cur[j]);
System.out.println();
for (int j = 0; j <= i; j++) prev[j] = cur[j];
}
}
public static void main(String[] args) {
generatePascalsTriangleAdditive(5);
}
}Optimization notes
Keep it simple. Prefer clear loops and method extraction before micro-optimizations.
Reuse computed values. Avoid recomputing the same sub-result inside nested loops.
❓ FAQ
🔄 Input / output examples
Use the sample programs as reference: provide valid numeric input and verify the output pattern matches the problem definition.
Edge cases
Smallest valid input
Confirm behavior for minimum accepted values.
Invalid input
Guard against non-numeric or out-of-range values when input is user-provided.
⏱️ Time and space complexity
Printing r rows requires O(r^2) time. Multiplicative method uses O(1) extra space beyond output; additive row-array method uses O(r).
Summary
- Pascal rows can be generated either via coefficients or previous-row sums.
- Both approaches print correct triangle values with nested loops.
- Complexity grows quadratically with the number of rows.
Each Pascal's Triangle entry equals a binomial coefficient: n choose k.
8 people found this page helpful
