32. Pascal's triangle

Pascal's triangle is a construction representing binomial coefficients. The triangle starts with a row that has a single value of 1. Elements of each row are constructed by summing the numbers above, to the left and right, and treating blank entries as 0. Here is an example of the triangle with five rows:

        1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

To print the triangle, we must:

  • Shift the output position to the right with an appropriate number of spaces, so that the top is projected on the middle of the triangle's base.
  • Compute each value by summing the above left and right values. A simpler formula is that for a row i and column j, each new value x is equal to the previous value of x multiplied by (i - j) / (j + 1), where x starts at 1.

The following is a possible implementation of a function that prints the triangle:

unsigned int number_of_digits(unsigned int const i)
{
return i > 0 ? (int)log10((double)i) + 1 : 1;
}

void print_pascal_triangle(int const n)
{
for (int i = 0; i < n; i++)
{
auto x = 1;
std::cout << std::string((n - i - 1)*(n / 2), ' '),
for (int j = 0; j <= i; j++)
{
auto y = x;
x = x * (i - j) / (j + 1);
auto maxlen = number_of_digits(x) - 1;
std::cout << y << std::string(n - 1 - maxlen - n%2, ' '),
}
std::cout << std::endl;
}
}

The following program asks the user to enter the number of levels and prints the triangle to the console:

int main()
{
int n = 0;
std::cout << "Levels (up to 10): ";
std::cin >> n;
if (n > 10)
std::cout << "Value too large" << std::endl;
else
print_pascal_triangle(n);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset