Pascal's Triangle in C++

Program to print Pascal's triangle

AdvancedPattern ProgramsExample 6 of 6
pascal-s-triangle.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int rows;
6
7 cout << "Enter number of rows: ";
8 cin >> rows;
9
10 for (int i = 0; i < rows; i++) {
11 int num = 1;
12 // Print spaces
13 for (int j = 0; j < rows - i - 1; j++) {
14 cout << " ";
15 }
16 // Print numbers
17 for (int j = 0; j <= i; j++) {
18 cout << num << " ";
19 num = num * (i - j) / (j + 1);
20 }
21 cout << endl;
22 }
23
24 return 0;
25}

Output

Enter number of rows: 5
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

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:

j=0: print 1, num = 1*(4-0)/1 = 4
j=1: print 4, num = 4*(4-1)/2 = 6
j=2: print 6, num = 6*(4-2)/3 = 4
j=3: print 4, num = 4*(4-3)/4 = 1
j=4: print 1

That's 1 4 6 4 1.

The visual "sum of the two parents" is true. This code never looks at the row above.