Triangle Rule
Edges & neighbors
Every row starts and ends with 1; each inner value is the sum of the two numbers above it.
Pascal’s triangle is a classic interview warm-up: nested loops, binomial coefficients, and clean printing. This tutorial covers the triangle rule, two generation methods, a live preview, algorithm steps, worked C examples, edge cases, and complexity.
Edges & neighbors
Every row starts and ends with 1; each inner value is the sum of the two numbers above it.
n choose k
Entry at row i, column j equals the binomial coefficient C(i, j).
In-row update
Update coeff = coeff * (i - j) / (j + 1) to walk a row without factorials.
Prev-row sums
Build each row from the previous list by adding adjacent neighbors.
1–14 rows
Pick a row count and draw a centered triangle instantly in the browser.
Complexity
Both methods print r rows in quadratic time; space differs by approach.
Pascal’s triangle starts with a single 1 at the top. Every row begins and ends with 1, and each middle value is the sum of the two numbers directly above it.
In code interviews you are usually asked to print the first r rows with spacing so the triangle looks centered. You can compute values with a multiplicative binomial update, or build each row from the previous one using neighbor sums.
It trains nested loops, careful indexing, and combinatorics without needing a factorial helper. The same numbers power binomial expansions and many DP warm-ups.
Row i has i + 1 entries (0-based), always edged with 1.
Position (i, j) is C(i, j) — useful beyond printing.
Multiplicative, additive, or fill a 2D array.
Values grow fast; C int can overflow — prefer long long for deeper rows.
In short: print r rows of Pascal’s triangle — edges are 1, insides are neighbor sums (or binomial updates) — and format spacing so the shape reads as a triangle.
Given a positive integer rows, print the first rows levels of Pascal’s triangle.
/* First 5 rows (conceptual shape)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1 */ | Item | Type | Description |
|---|---|---|
rows | int | Number of triangle rows to print (must be ≥ 1 for a visible triangle). |
| Printed output | text | Centered rows of integers with fixed-width spacing. |
for i from 0 to rows - 1:
print leading spaces
coeff = 1
for j from 0 to i:
print coeff
coeff = coeff * (i - j) / (j + 1) | Method | Idea | Extra space |
|---|---|---|
| Multiplicative | Update binomial coefficient along the row | O(1) |
| Additive | Sum neighbors from the previous row list | O(rows) |
| Goal | Pattern |
|---|---|
| Next binomial in a row | coeff = coeff * (i - j) / (j + 1) |
| Inner cell from previous row | cur[j] = prev[j - 1] + prev[j] |
| Leading spaces | printf(" ") in a loop |
| Fixed-width number | printf("%6d", coefficient) |
| Row length | Row i has i + 1 values (0-based) |
All can print the triangle — but clarity and cost differ.
in-row updateNo factorial calls; compact and O(1) extra space
prev + prevMatches the geometric definition; keeps a previous row
factorialsWorks but slower and easier to get wrong for beginners
explain bothKnow the rule first, then pick a clean implementation
Reach for Pascal’s triangle drills when nested loops and binomial thinking matter.
Quick check of loops, indexing, and formatted output.
Connect printed numbers to C(n, k) without heavy math libraries.
Additive rows resemble filling a DP table from previous states.
Outer row loop + inner column loop with a clear visual result.
Deep triangles explode in size — cap previews and discuss big integers.
Key benefit: one visual problem that covers loops, math, formatting, and complexity in a short exercise.
Choose a row count between 1 and 14 and draw the triangle in the browser.
Three complete C programs — multiplicative update, additive row construction, and a 2D array fill. Click View Output to reveal sample console results.
Print five rows with clean spacing.
Classic direct coefficient generation for each row — no factorial helper required.
#include <stdio.h>
void generatePascalsTriangle(int rows) {
for (int i = 0; i < rows; i++) {
int coefficient = 1;
for (int j = 0; j < rows - i - 1; j++) {
printf(" ");
}
for (int j = 0; j <= i; j++) {
printf("%6d", coefficient);
coefficient = coefficient * (i - j) / (j + 1);
}
printf("\n");
}
}
int main(void) {
generatePascalsTriangle(5);
return 0;
} Each row starts with coefficient = 1. After printing a value, the next coefficient is updated with coeff * (i - j) / (j + 1), which stays exact for binomial rows when using integer division. Leading spaces keep the triangle centered.
Build rows from the geometric definition.
Directly follows the sum-of-two-above definition using arrays. Uses long long for more headroom.
#include <stdio.h>
#define MAXR 64
void generatePascalsTriangleAdditive(int rows) {
long long prev[MAXR] = {0};
long long cur[MAXR];
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 j = 0; j < rows - i - 1; j++) {
printf(" ");
}
for (int j = 0; j <= i; j++) {
printf("%6lld", cur[j]);
}
printf("\n");
for (int j = 0; j <= i; j++) {
prev[j] = cur[j];
}
}
}
int main(void) {
generatePascalsTriangleAdditive(5);
return 0;
} Set edges to 1, then fill middle cells with prev[j - 1] + prev[j]. Copy cur into prev for the next iteration. Needs O(rows) extra memory for two row buffers.
Many prompts ask you to fill a 2D array instead of only printing.
Store the triangle in triangle[i][j], then print — useful when later code needs the values again.
#include <stdio.h>
#define MAXR 32
void fillPascalsTriangle(long long triangle[][MAXR], int rows) {
for (int i = 0; i < rows; i++) {
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
}
int main(void) {
int rows = 5;
long long triangle[MAXR][MAXR] = {{0}};
fillPascalsTriangle(triangle, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
printf("%lld%s", triangle[i][j], (j == i) ? "" : " ");
}
printf("\n");
}
return 0;
} Same additive rule as Example 2, but each finished row lives in triangle[i]. Storing data is useful when a later step needs C(n, k) without recomputing; printing is for console demos.
For row i from 0 to rows - 1, print leading spaces first.
Either update the coefficient formula or sum neighbors from the previous row.
Output numbers with fixed-width fields, then a newline.
After the last row, the centered Pascal triangle is fully printed.
i = 4Trace the multiplicative update for the fifth printed row (0-based i = 4). Start with coeff = 1, then apply coeff = coeff * (i - j) / (j + 1) after each print.
j | Update after print | Next coeff | |
|---|---|---|---|
0 | 1 | 1 * (4 - 0) / (0 + 1) | 4 |
1 | 4 | 4 * (4 - 1) / (1 + 1) | 6 |
2 | 6 | 6 * (4 - 2) / (2 + 1) | 4 |
3 | 4 | 4 * (4 - 3) / (3 + 1) | 1 |
4 | 1 | (row ends) | — |
Printed row: 1 4 6 4 1 — exactly C(4, 0) … C(4, 4).
Where Pascal’s triangle (and its rows) show up beyond the interview prompt.
Read “n choose k” values without writing a factorial helper.
Example: C(5, 2) = 10 from row 5.
Coefficients of (a + b)n are exactly row n.
Example: (a+b)³ → 1, 3, 3, 1.
Builds intuition for tabulation from previous states.
Example: each cell depends on two parents above.
Nested loops plus formatting practice for beginners.
Example: centered print with fixed-width fields.
Binomial probabilities reuse the same coefficients.
Example: fair-coin paths of length n.
Shows why off-by-one bugs appear at triangle edges.
Example: middle loop runs only for 1..i-1.
Pro Tip: if the interviewer asks for a 2D array, fill then use; if they ask to “print the triangle,” prioritize readable spacing after correct values.
Why these two generation styles earn interview points.
Computes a full row with O(1) extra memory and no previous-row storage.
Neighbor sums are easy to explain on a whiteboard from the geometric rule.
Avoids huge intermediate products from computing n! / (k!(n-k)!) directly.
The multiplicative step stays exact when you keep integer types and multiply before dividing.
Pro Tip: lead with the additive story for clarity, then mention the multiplicative update as the space-leaner variant.
Small habits that keep Pascal code clean in interviews.
Ask whether the judge wants console output or a filled 2D array before writing formatting code.
Set edges to 1, then fill only middle indices — fewer off-by-one bugs.
/Keep operands as int/long long so / is integer division — never cast to float mid-update.
Decide whether row 0 or row 1 is the top, and stick to that in comments and loops.
Get values right first; spacing is polish for human-readable demos.
Pro Tip: dry-run one small row on paper (like i = 4 above) before coding — it catches formula mistakes fast.
Mistakes that commonly break Pascal triangle solutions.
Casting to float mid-update can introduce rounding and wrong later coefficients.
→ Keep the multiplicative update in integer arithmetic (long long if needed).
Looping j = 0..i for middle fills overwrites edges or skips cells.
→ For additive rows, update only j = 1 .. i-1.
Editing prev[] while reading it corrupts neighbor sums.
→ Build a new cur[] each iteration (or copy carefully).
Computing C(n, k) via full factorials is slower and messier than needed.
→ Prefer multiplicative or additive construction.
rows ≤ 0 should return empty / error per the prompt — not crash mid-loop.
→ Validate early; for storage APIs, leave the array unused / return early.
Check these inputs before calling the solution done.
Output is just 1 (or a single stored cell for array APIs).
Print nothing or skip the fill — match the problem statement.
rows < 0Treat as invalid; reject input or print nothing depending on requirements.
C fixed-width ints overflow — use long long, widen print fields, or cap r.
Confirm whether “n rows” means indices 0..n-1 or 1..n.
Large numbers overflow %6d-style fields — widen or skip centering.
Handy facts interviewers sometimes ask as follow-ups.
n (0-based) is 2n.n is the coefficient list for (a + b)n.Try these variations to lock in the pattern.
nrows in {0, 1, 5}1 << i (or pow(2, i))long long or limit rows in C./ is correct for the multiplicative update when types stay integral — each step is exact.rows > 0 before printing; rows = 1 should print a single 1.Quick Takeaway: edges are 1, insides are neighbor sums (or binomial updates), and printing r rows costs O(r²).
| Program | Time | Extra space |
|---|---|---|
| Multiplicative method | O(rows²) | O(1) |
| Additive row method | O(rows²) | O(rows) |
| 2D array storage | O(rows²) | O(rows²) (stores all cells) |
Pascal’s triangle is a small nested-loop exercise with big teaching payoff: binomial coefficients, careful indexing, and readable output. Master both the multiplicative update and the additive prev-row approach so you can explain either in an interview.
Practice the three examples above, then continue to perfect numbers for another classic number-theory check.
Edges are 1, insides are neighbor sums — keep the update in integer arithmetic (prefer long long), and validate row counts before printing.
/ (multiply before divide) for binomial updatesrows ≥ 1 (or handle empty output explicitly)rows = 1 edge casePrint rows the interview-friendly way.
Edges 1, insides sum
DefinitionC(i, j) at cell
MathIn-row coeff update
CodePrev-row neighbors
CodeO(r²) time
AnalysisEach entry in Pascal’s triangle is a binomial coefficient “n choose k”—the same numbers that show up in the expansion of (a + b)n.
Learn how to check whether a number equals the sum of its proper divisors.
8 people found this page helpful