Solutions
Here are the solutions for the above problem-solving sections.
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 columnj
, each new valuex
is equal to the previous value ofx
multiplied by(i - j) / (j + 1)
, wherex
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) { ...