 Index Books FAQ Contact About Rod   # Title: Display Pascal's triangle in C# In Pascal's triangle, each row has a 1 on either end. An entry between the ends is the sum of the two entries above it. Mathematically you can define the Nth entry on row R as:

`    Entry(R, N) = Entry(R - 1, N - 1) + Entry(R - 1, N)`

This triangle has some interesting properties. For example, if you raise the polynomial (X + Y) to the Nth power, then the Nth row of the triangle gives you the coefficients for the different combinations of XN * YM. The Nth entry on row R also gives the number of ways you can flip a coin R times and come up with heads in N of them.

This example uses the following code to generate a printout of the first 28 rows of Pascal's triangle. Even starting with a 4 point font, the triangle grows too big to display after that many rows.

// Draw the triangle. private void pdocTriangle_PrintPage(object sender, PrintPageEventArgs e) { using (Font font = new Font("Courier New", 4)) { using (StringFormat format = new StringFormat()) { // Center each line. format.Alignment = StringAlignment.Center; const float width_factor = 6.5f; int num_wid = (int)(width_factor * e.Graphics.MeasureString("0", font).Width); int num_hgt = (int)e.Graphics.MeasureString("0", font).Height; int y = e.MarginBounds.Top; int xmid = (e.MarginBounds.Left + e.MarginBounds.Right) / 2; // Make the first row. List numbers = new List(); numbers.Add(1); // Display rows. while (y < e.MarginBounds.Height) { int x = xmid - (num_wid * numbers.Count) / 2; if (x < e.MarginBounds.Left) break; // Display the current list of numbers. foreach (int num in numbers) { e.Graphics.DrawString(num.ToString(), font, Brushes.Black, x, y, format); x += num_wid; } // Add the next number to the list. List new_numbers = new List(); new_numbers.Add(1); for (int i = 1; i < numbers.Count; i++) { new_numbers.Add(numbers[i - 1] + numbers[i]); } new_numbers.Add(1); numbers = new_numbers; y += num_hgt; } } } }

The code starts by creating a tiny font and a StringFormat object to center printed text. It then adds the value 1 to a List to represent the triangle's first row.

Now the code enters a loop to display rows. It sets the value x to the position where the leftmost number on that row should be and loops through the numbers displaying them.

The code then uses the current row to create the next row in the triangle and repeats the loop to display it. The program ends when the rows are too wide to fit on the page.

If you like, you can print the result, laminate it, and keep it as a handy cheat-sheet for those all-to-frequent times when you really need to know the 9th term in the 20th row of the triangle. ;-)

Download the example to experiment with it and to see additional details.