Pascal Triangle

The following code sample shows how to create pascaltriangle

using System;
using System.Collections.Generic;

class PascalTriangle
{
static void Main()
{
foreach (uint[] row in GetPascalTriangle())
{
Print(row);
Console.ReadKey();
}
}

static void Print(uint[] row)
{
foreach (uint e in row)
Console.Write(“{0}\t”, e);
Console.WriteLine();
}

static IEnumerable GetPascalTriangle()
{
uint[] row = new uint[1] { 1 };

for(int n = 2; ; n++)
{
yield return row;

uint[] nrow = new uint[n];
Array.Copy(row, nrow, n-1);
for (int i = 1; i < n; i++)
nrow[i] += row[i-1];
row = nrow;
}
}
}

Advertisements
%d bloggers like this: