How to create 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;
}
}
}


Comments

Author: Kapil Dhawan18 Jun 2008 Member Level: Gold   Points : 2

Hello
Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good code from your side
This code will help lots of guys
Thanks to you
Regards,
Kapil

Guest Author: Dale04 Apr 2013

Hello
Nice piece of code
Thanks for sharing your knowledge with us.
Please help me understand this snippet
for (int n = 2; ; n++)
Why no condition in this for statement?
Dale



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: