Monday, February 4, 2013

Pascal Triangle (C#)

Write a program to generate a Pascal triangle and print all the numbers on the 11th row

The Pascal triangle is represented in the diagram below :


public class Pascal
{
public void DrawTriangle(int n)
{
//validations
if (n == 0)
{
Console.WriteLine("Drawing pascal triangle");
Console.WriteLine(1);
}
else if (n == 1)
{
Console.WriteLine("Drawing pascal triangle");
Console.WriteLine(1);
Console.WriteLine(Environment.NewLine);
Console.WriteLine("{0},{1}", 1, 1);
}
else if (n < 0)
{
Console.WriteLine("Invalid row count!!");
}
//Implement the triangle
else
{
int[,] triangle = new int[n, n];
triangle[0, 0] = 1;
triangle[1, 0] = 1;
triangle[1, 1] = 1;
for (int i = 2; i < n; i++)
{
triangle[i, 0] = 1;
triangle[i, i] = 1;
for (int j = 1; j < n; j++)
{
triangle[i, j] = (triangle[i - 1, j - 1] + triangle[i - 1, j]);
}
}
for (int x = 0; x < triangle.GetLength(0); x++)
{
for (int y = 0; y < triangle.GetLength(1); y++)
{
if (triangle[x, y] != 0)
Console.Write(triangle[x, y] + " ");
}
Console.WriteLine();
}
}
}
}

Calling the method and printing the 11th row
static void Main(string[] args)
{
Pascal P = new Pascal();
P.DrawTriangle(11);
Console.ReadKey();
}

No comments: