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.
The source code in C++ is given as follows:
#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:
- Teaching Kids Programming – Pascal Triangle Algorithms and Applications
- Coding Exercise – Pascal Triangle II – C++ and Python Solution
- How to Print Pascal Triangle in C++ (with Source Code)
- Compute the Nth Row of a Pascal’s Triangle using Dynamic Programming Algorithm
- GoLang: Generate a Pascal Triangle
–EOF (The Ultimate Computing & Technology Blog) —
500 wordsLast Post: Duplicate a MySQL table - Copy Table / Duplicate Database / PHP Script
Next Post: Loop Implementation at Windows Batch Programming
