Pascal's Triangle in C++
Program to print Pascal's triangle
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}
Output
Enter number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1What'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.