How to Print Pascal Triangle in C++ (with Source Code)


Pascal Triangle is a triangle made of numbers. The first row (root) has only 1 number which is 1, the second row has 2 numbers which again are 1 and 1. The third row has 3 numbers, which is 1, 2, 1 and so on. Each number equals to the sum of two numbers at its shoulder. The numbers at edges of triangle will be 1.

6104da09ef30a948a90e0b43067d9a99 How to Print Pascal Triangle in C++ (with Source Code) algorithms c / c++ math

The source code in C++ is given as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
 
using namespace std;
 
const int N = 12;
 
long getNum(int n, int r) {
    int i;
    long p = 1;
    for(i = 1; i <= r; i++) {
        p = p * (n - i + 1) / i;
    }
    return p;
}
 
void print() {
    int n, r, t, i;
    for(n = 0; n <= N; n++) {
        for(r = 0; r <= n; r++) {
            if(r == 0) {
                for(i = 0; i <= N - n; i++) {
                    cout << " ";
                }
            } else {
                cout << " ";
            }
            cout.width(3); // three characters width
            cout << getNum(n, r);
            cout.width(1);
        }
        cout << endl;
    }
}
 
int main() {
    cout << "Pascal Triangle,  http://HelloACM.com" << endl << endl;
    print();
    return 0;
}
#include <iostream>

using namespace std;

const int N = 12;

long getNum(int n, int r) {
    int i;
    long p = 1;
    for(i = 1; i <= r; i++) {
        p = p * (n - i + 1) / i;
    }
    return p;
}

void print() {
    int n, r, t, i;
    for(n = 0; n <= N; n++) {
        for(r = 0; r <= n; r++) {
            if(r == 0) {
                for(i = 0; i <= N - n; i++) {
                    cout << " ";
                }
            } else {
                cout << " ";
            }
            cout.width(3); // three characters width
            cout << getNum(n, r);
            cout.width(1);
        }
        cout << endl;
    }
}

int main() {
    cout << "Pascal Triangle,  http://HelloACM.com" << endl << endl;
    print();
    return 0;
}

The function getNum takes two parameters, n and r which correspond to the position in the triangle.

Another posts on Pascal Triangles: Compute the Nth Row of a Pascal’s Triangle using Dynamic Programming Algorithm and Coding Exercise – Pascal Triangle II – C++ and Python Solution

Pascal Triangle Implementations:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
517 words
Last Post: Duplicate a MySQL table - Copy Table / Duplicate Database / PHP Script
Next Post: Loop Implementation at Windows Batch Programming

The Permanent URL is: How to Print Pascal Triangle in C++ (with Source Code)

Leave a Reply