Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Pascal’s Triangle in C
Build Pascal’s triangle with cooperating functions in this free C programming course lecture, and learn why correct code can still overflow.
Welcome to another lecture in our free C programming course. Today you will build Pascal’s triangle in C out of small cooperating functions, and you will discover why a perfectly correct formula can still print garbage once the numbers grow. This free C tutorial treats the triangle as a practical lesson in embedded C programming: choosing integer types, avoiding overflow, and splitting one problem across functions that each do exactly one job. By the end you will own three working ways to compute binomial coefficients and a clear rule for choosing between them.
Pascal’s triangle looks like a classroom curiosity, but the program behind it is a compact tour of everything this chapter has taught: a function that calls another function, a helper that is reused many times, loops driving output formatting, and a hidden trap in the data type. Every one of those ideas shows up daily when you write firmware.
What You Will Learn in This Free C Programming Course Lecture
- How each entry of Pascal’s triangle maps to the binomial coefficient nCr.
- How to layer a program into a printing function, a combination function and a factorial helper.
- Why the factorial method fails silently for n of 21 and above on a 64-bit unsigned type, and much earlier on small MCUs.
- Two overflow-resistant alternatives: the stepwise multiply-divide loop and the addition-only row update.
- How to read a comparison table of cost, range and clarity before choosing an algorithm for embedded targets.
- How to compile with strict warnings and verify your triangle against an independent method.
Prerequisites
You should be comfortable with function declarations, return values and passing arguments, all covered earlier in the Functions chapter. You also need the basic loop statements, the idea of a data type having a fixed width, and printf field widths from the input-output chapter. If recursion still feels new, do not worry: this lecture uses plain loops, and the next lectures return to recursion with digit problems. Everything you have met so far in this free C programming course is enough to follow along.
What Pascal’s Triangle Actually Contains
Row 0 holds a single 1. Every later row starts and ends with 1, and every inner number is the sum of the two numbers directly above it. That one sentence is the entire definition, yet it hides a second, more useful description: the entry at row n and position r equals the number of ways to choose r items from n distinct items. Mathematicians write it as C(n, r), and C programmers usually call the function comb or ncr.
| Row n | Entries C(n, 0) to C(n, n) | Row sum |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 1 1 | 2 |
| 2 | 1 2 1 | 4 |
| 3 | 1 3 3 1 | 8 |
| 4 | 1 4 6 4 1 | 16 |
| 5 | 1 5 10 10 5 1 | 32 |
Notice three properties you can use as test oracles later. Each row is symmetric, so C(n, r) equals C(n, n-r). Each row sums to a power of two, namely 2 raised to n. And the addition rule C(n, r) = C(n-1, r-1) + C(n-1, r) holds everywhere inside the triangle. When your program prints something that breaks any of these, you know the arithmetic went wrong before you even look at the code.
Designing the Program as Three Layers
A beginner often writes the whole triangle inside main. A better design separates responsibilities, which is exactly why functions exist. The top layer decides how the triangle looks: how many rows, how much padding, which field width. The middle layer answers a pure mathematical question, “what is C(n, r)?”. The bottom layer is a helper that computes a factorial. Because each layer exposes only a small interface, you can test the middle layer on its own and swap its algorithm without touching the printing code.
Each printed entry costs three factorial calls and one division. For a seven-row triangle that is twenty-eight entries and eighty-four factorial calls, each one running a loop. The program is correct, but it is doing a lot of repeated work, and that is the first hint that the formula is not the only way to build the triangle.
Method 1: The Textbook Factorial Formula
The direct translation of the formula uses a helper that multiplies all integers from 2 up to k. Notice that the helper returns 1 for any k below 2, which conveniently handles zero factorial.
typedef unsigned long long u64;
static u64 fact(int k)
{
u64 f = 1;
while (k > 1) {
f *= (u64)k;
k--;
}
return f;
}
static u64 ncr_factorial(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}
Reading it top to bottom: fact counts the argument down while accumulating a product, and ncr_factorial divides the numerator by the product of two smaller factorials. Both are marked static because nothing outside this file needs them, a habit that keeps embedded code modules tidy and lets the compiler inline aggressively.
The Overflow Trap: Where Correct Code Gives Wrong Answers
Factorials grow explosively. The helper multiplies in a fixed-width type, and once the true value exceeds what the type can store, the result silently wraps around. For unsigned types the wrap is well defined and deterministic. For signed types, overflow is undefined behaviour, which is worse because the compiler may assume it never happens and optimise accordingly.
| Type width | Largest value | Largest n where n! fits |
|---|---|---|
| 16-bit signed | 32,767 | 7 (5,040) |
| 16-bit unsigned | 65,535 | 8 (40,320) |
| 32-bit signed | 2,147,483,647 | 12 (479,001,600) |
| 32-bit unsigned | 4,294,967,295 | 12 |
| 64-bit signed | about 9.22 x 10^18 | 20 |
| 64-bit unsigned | about 1.84 x 10^19 | 20 |
This table matters for embedded work because the width of int and long is chosen by the platform. A classic 8-bit or 16-bit microcontroller toolchain may give you a 16-bit int, so a factorial helper written with plain int breaks at 8!. On 64-bit Linux, long is 64 bits wide, while on 64-bit Windows and on 32-bit targets it is 32 bits wide. Code that works on your laptop can therefore fail on the board. Fixed-width types from stdint.h remove the guessing.
Method 2: Stepwise Multiply and Divide
You can avoid giant intermediate values by interleaving multiplication and division. Start with 1, then for i from 1 to r multiply by (n – r + i) and divide by i. The division is always exact because after step i the running value equals C(n – r + i, i), an integer, so no remainder is ever thrown away. Before looping, replace r with n – r when that is smaller, using the symmetry property; this halves the work and keeps the intermediate product small.
static u64 ncr_stepwise(int n, int r)
{
u64 value = 1;
int i;
if (r > n - r)
r = n - r;
for (i = 1; i <= r; i++)
value = value * (u64)(n - r + i) / (u64)i;
return value;
}
The multiplication happens before the division in each step, so precedence and left-to-right evaluation matter here. Dividing first would truncate and give wrong results. Because this function needs at most min(r, n-r) multiplications and the same number of divisions, it is both faster and far more range-friendly than the factorial formula.
Method 3: Addition Only, Row by Row
The triangle’s own definition suggests the cheapest algorithm of all: keep one row in an array and turn it into the next row by addition. The trick is the update order. If you walk left to right, you overwrite a value you still need. Walking from the right end toward the left means each element is updated using its still-unmodified left neighbour.
static void next_row(u64 *row, int r)
{
int i;
for (i = r; i > 0; i--)
row[i] += row[i - 1];
}
| Step | Index updated | Operation | Array afterwards |
|---|---|---|---|
| start | none | row 4 loaded | 1 4 6 4 1 0 |
| 1 | 5 | 0 + 1 | 1 4 6 4 1 1 |
| 2 | 4 | 1 + 4 | 1 4 6 4 5 1 |
| 3 | 3 | 4 + 6 | 1 4 6 10 5 1 |
| 4 | 2 | 6 + 4 | 1 4 10 10 5 1 |
| 5 | 1 | 4 + 1 | 1 5 10 10 5 1 |
This method uses no multiplication, no division and no factorial, so it is ideal for microcontrollers without a hardware divider. Cortex-M0 class cores, for example, have no divide instruction, so every / becomes a call into a library routine, and 64-bit division is slower still. Addition costs one cycle.
Comparing Three Methods in This Free C Tutorial
| Criterion | Factorial formula | Stepwise loop | Addition row |
|---|---|---|---|
| Work per entry | about 3n multiplications, 1 division | at most n/2 multiplies and divides | 1 addition |
| Overflow starts at | n of 21 (64-bit) | when the true value overflows | when the true value overflows |
| RAM needed | none | none | one row array |
| Random access to one C(n, r) | yes | yes | no, must build all rows |
| Best for | teaching the formula | single coefficient queries | printing or tables |
Complete Free C Programming Course Program with Real Output
The listing below runs all three methods, cross-checks the addition method against the stepwise method for 34 rows, and then deliberately walks into the overflow trap. It is written for C99 and compiled with strict warnings.
#include <stdio.h>
typedef unsigned long long u64;
/* Method 1: the textbook formula n! / (r! * (n-r)!) */
static u64 fact(int k)
{
u64 f = 1;
while (k > 1) {
f *= (u64)k;
k--;
}
return f;
}
static u64 ncr_factorial(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}
/* Method 2: multiply then divide one step at a time; every step is exact */
static u64 ncr_stepwise(int n, int r)
{
u64 value = 1;
int i;
if (r > n - r)
r = n - r;
for (i = 1; i <= r; i++)
value = value * (u64)(n - r + i) / (u64)i;
return value;
}
/* Method 3: build a row from the previous row using addition only */
static void next_row(u64 *row, int r)
{
int i;
for (i = r; i > 0; i--)
row[i] += row[i - 1];
}
int main(void)
{
int rows = 7, r, c, n;
u64 row[40] = {1};
int bad = 0;
puts("Pascal's triangle, 7 rows (stepwise nCr)");
for (r = 0; r < rows; r++) {
for (c = 0; c < (rows - 1 - r) * 2; c++)
putchar(' ');
for (c = 0; c <= r; c++)
printf("%4llu", ncr_stepwise(r, c));
putchar('\n');
}
for (n = 0; n < 34; n++) {
if (n > 0)
next_row(row, n);
for (c = 0; c <= n; c++)
if (row[c] != ncr_stepwise(n, c))
bad++;
}
printf("\naddition vs stepwise, rows 0..33, mismatches: %d\n\n", bad);
puts(" n r factorial method stepwise method same?");
for (n = 19; n <= 24; n++) {
u64 a = ncr_factorial(n, n / 2);
u64 b = ncr_stepwise(n, n / 2);
printf("%4d %3d %20llu %20llu %s\n", n, n / 2, a, b, a == b ? "yes" : "NO");
}
printf("\n20! = %llu\n", fact(20));
printf("21! wraps to %llu\n", fact(21));
return 0;
}
Build and run it exactly like this:
gcc -std=c99 -Wall -Wextra -pedantic -o pascal pascal.c
./pascal
This is the output from a real run:
Pascal's triangle, 7 rows (stepwise nCr)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
addition vs stepwise, rows 0..33, mismatches: 0
n r factorial method stepwise method same?
19 9 92378 92378 yes
20 10 184756 184756 yes
21 10 98014 352716 NO
22 11 10792 705432 NO
23 11 425 1352078 NO
24 12 46 2704156 NO
20! = 2432902008176640000
21! wraps to 14197454024290336768
Study the last table carefully. Up to n of 20 both columns agree. At n of 21 the factorial column collapses to 98,014 when the true answer is 352,716, and it keeps shrinking toward nonsense while the stepwise column stays exact. The final two lines show why: 20 factorial still fits in 64 unsigned bits, but 21 factorial wraps to a number that has nothing to do with the real product.
Embedded C Programming Use Cases
Binomial coefficients are not only a classroom exercise. Row 4 of the triangle is 1, 4, 6, 4, 1, and the entries sum to 16. Dividing by 16 turns it into a smoothing filter whose weights approximate a Gaussian; because 16 is a power of two, the division is just a right shift by four bits. Firmware engineers use exactly this binomial low-pass filter to clean noisy ADC samples without floating point. Larger rows give stronger smoothing. Combinatorics also appears when you count test combinations for a configuration matrix or estimate the probability of a given number of bit errors in a packet.
Common Mistakes and Troubleshooting
Almost every learner in a free C programming course hits one of the traps below at least once, so use this table as a debugging checklist.
| Symptom | Likely cause | Fix |
|---|---|---|
| Numbers go wrong after row 12 or 13 | int or 32-bit long used for factorial | Use a 64-bit unsigned type or switch to the stepwise or addition method |
| printf shows huge or negative numbers | Wrong conversion specifier for the type | Match specifier to type, for example %llu for unsigned long long |
| Triangle rows contain duplicated values | Row updated left to right | Update from the right end toward index 1 |
| Stepwise result is off by a little | Division performed before multiplication | Multiply first, then divide, in each step |
| comb(n, r) returns 1 when r is larger than n | Helper returns 1 for negative arguments | Validate that 0 <= r <= n before calling |
| Output is crooked | Padding and field width disagree | Use a fixed width such as %4llu and pad by twice the rows remaining |
Best Practices, Performance and Security
- Pick the integer type on purpose and write it down in a comment or a typedef, as the listing does with
u64. - Prefer the algorithm that keeps intermediate values small; range problems usually appear in the middle of a calculation, not at the end.
- Test with an independent oracle. The listing compares two methods for every entry of 34 rows, which found zero mismatches.
- Compile with
-Wall -Wextra -pedanticand treat warnings as defects. - Performance: on cores without a divider, avoid division inside loops. The addition method has no division at all.
- Security: unchecked integer overflow is a well-known source of memory-safety bugs, especially when a computed value becomes a buffer size. GCC and Clang provide
__builtin_mul_overflowto detect it. Never let an overflowed count size an allocation.
Key Takeaways and Conclusion
Key takeaways
- An entry of Pascal’s triangle is the binomial coefficient C(n, r), and each row is symmetric and sums to a power of two.
- Splitting a program into printing, combination and factorial functions makes each part testable on its own.
- The factorial formula is mathematically correct but overflows quickly; 21 factorial already wraps a 64-bit unsigned type.
- The stepwise loop and the addition update keep numbers small, and the addition method needs neither multiplication nor division.
- Always know the real width of your integer types on the target board.
- A good free C programming course teaches you to test every algorithm against a second method.
You started with a pretty pattern and ended with a lesson that every firmware developer eventually learns the hard way: an algorithm is only as good as the range of the numbers flowing through it. Three methods solved the same problem with very different costs, and a tiny real run exposed the weakness of the most familiar one. That habit of questioning ranges, testing against a second method and choosing the data type deliberately is what turns a student exercise into production quality embedded C programming. This free C programming course will keep returning to it, and the next lecture applies the same discipline to converting numbers into Roman numerals with a table-driven function.
Frequently Asked Questions: Pascal’s Triangle in C
What is Pascal’s triangle in C programming?
It is a triangular table where each row starts and ends with 1 and every inner entry is the sum of the two entries above it. Each entry equals the binomial coefficient C(n, r), so a C program can build it either from a formula or from simple addition.
Why does the factorial method print wrong numbers for larger rows?
Factorials grow so quickly that the intermediate values exceed the integer type. With a 64-bit unsigned type, 21 factorial already wraps around, so the final division returns a wrong but plausible-looking value.
Which method is best for embedded targets?
The addition-only row update is usually best for printing a whole triangle because it needs no multiplication or division, which matters on cores without a hardware divider. The stepwise loop is better when you need one coefficient on demand.
Why must the row array be updated from right to left?
Each element becomes itself plus its left neighbour. Updating from the left would overwrite a neighbour before it has been used, so the right-to-left order preserves the old values that are still needed.
Which integer type should I use for binomial coefficients?
Use a fixed-width unsigned type such as uint64_t and choose the algorithm that keeps intermediate values small. Never rely on int or long, because their width changes between platforms.
Is this free C programming course suitable for beginners?
Yes. Each lecture explains the idea in plain language first, then shows tested code with real output, and finishes with the deeper embedded considerations for readers who want them.
How do I centre the printed triangle?
Print two spaces for every row remaining below the current one, then print each entry in a fixed field width such as four characters. The listing in this lecture shows the exact loop.
Keep Building Your C Skills
Continue this free C programming course with the next lecture on Roman numerals, and practise every example on your own machine.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments