In mathematics, Pascal's triangle is a triangular arrangement of numbers that gives the coefficients in the expansion of any binomial expression, such as (x + y)n
. It is named for the 17th-century French mathematician Blaise Pascal. As an easier explanation for those who are not familiar with binomial expression, the pascal's triangle is a never-ending equilateral triangle of numbers that follow a rule of adding the two numbers above to get the number below.
In this article, we'll show you how to generate this famous triangle in the console with the Swift programming language.
Printing directly in the console
Graphically, the way to build the pascals triangle is pretty easy, as mentioned, to get the number below you need to add the 2 numbers above and so on:
The following code will generate the pascal's triangle in C++:
#include <iostream>
#include <conio.h>
using namespace std;
void printPascal(int n)
{
for (int line = 1; line <= n; line++)
{
// used to represent C(line, i)
int C = 1;
for (int i = 1; i < (n - line + 1); i++){
cout << " ";
}
for (int i = 1; i <= line; i++)
{
// The first value in a line is always 1
cout << C << " ";
C = C * (line - i) / i;
}
cout << "\n";
}
}
// Execution
int main()
{
int n;
cout << "Please provide the number of rows of the triangle: ";
cin >> n;
printPascal(n);
// Pause console
_getch();
return 0;
}
The program will prompt for an integer on the console that defines the number of rows that the triangle will have.
Happy coding !