Pascal's Triangle in C++
Print Pascal's triangle in C++ with the running formula num = num * (i - j) / (j + 1). Explains binomial coefficients and why multiplying first stays exact.
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 for (int i = 0; i < rows; i++) {11 int num = 1;12 // Print spaces13 for (int j = 0; j < rows - i - 1; j++) {14 cout << " ";15 }16 // Print numbers17 for (int j = 0; j <= i; j++) {18 cout << num << " ";19 num = num * (i - j) / (j + 1);20 }21 cout << endl;22 }2324 return 0;25}
Sample Output
1
Row 0.
1 4 6 4 1
Row 4: C(4,0) to C(4,4).
In this one
- What binomial coefficients are
- How each row can be built left to right without the previous row
- Why multiply-then-divide stays exact with ints
- How the padding centers each row
How it works
- 1
Read rows (5).
- 2
For each row i from 0, reset num = 1.
- 3
Print rows - i - 1 spaces.
- 4
For j = 0 to i: print num, then num = num * (i - j) / (j + 1).
- 5
End the row.
Edge cases
Large rows
Enter 35.
num * (i - j) overflows int before the division for big rows, so values go wrong. Use long long.
Divide first
Write num / (j + 1) * (i - j).
Integer division truncates early, so some entries become wrong, for example row 5 gives a wrong middle value.
What's going on
Pascal's triangle: each entry is a binomial coefficient. Row i (counting from 0) is C(i,0) C(i,1) … C(i,i). 5 rows: 1 / 1 1 / 1 2 1 / 1 3 3 1 / 1 4 6 4 1.
This program does not add the two numbers above. It walks the row with:
num = num * (i - j) / (j + 1)
for (int i = 0; i < rows; i++) — 0-based. i < rows not <=.
Pad: j < rows - i - 1 spaces, then the numbers.
int num = 1; at the start of each row. Always print 1 first.
Then for j from 0 to i: print num, then update. Multiply before divide so integer math stays exact: num * (i - j) / (j + 1). Reverse that (num / (j+1) * (i-j)) and 4/2 is fine but 5/2 truncates and the row is wrong.
Walk i = 4:
That's 1 4 6 4 1.
The visual "sum of the two parents" is true. This code never looks at the row above.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is row index 3 (0-based)?
Pick an answer to check it.
Question 2
Why multiply before dividing?
Pick an answer to check it.
Questions people ask
Why does each row start with 1?
C(i, 0) is always 1, so num is reset to 1 at the start of every row.
Is this the same as adding the two numbers above?
Yes, both give the same values. This code uses a formula so it does not need to store the previous row.
Where is Pascal's triangle used?
Counting combinations and expanding (a + b)^n.