Example 1 — Additive Rows
Keep the previous row and build the next by summing adjacent values.
function printPascal(rows) {
if (rows <= 0) {
console.log("Enter a positive number of rows.");
return;
}
let prev = [1];
console.log(prev.join(" "));
for (let i = 1; i < rows; i++) {
const curr = [1];
for (let j = 1; j < prev.length; j++) {
curr.push(prev[j - 1] + prev[j]);
}
curr.push(1);
console.log(curr.join(" "));
prev = curr;
}
}
printPascal(5); How It Works
- Reject non-positive row counts before looping.
- Start with
prev = [1]— the top of the triangle. - Each new row begins and ends with
1. - Inner values are
prev[j - 1] + prev[j]— the classic “two parents” rule. - Replace
prevwithcurrand repeat untilrowslines are printed.
