Pascal's Triangle

CSharp · Console

/Program.cs

using System;

public class Program
{
	public static void Main()
	{
		//Please change the parameter to a number less than 10
		PascalTriangle(1);
	}

	// factorial
	static int fact(int n)
	{
		int x = 1;
		while (n > 1)
		{
			x = x * n;
			n = n - 1;
		}

		return x;
	}

	// combinations
	static int comb(int n, int r)
	{
		int x = fact(n) / (fact(n - r) * fact(r));
		return x;
	}

	// Pascal's triangle
	static void PascalTriangle(int n)
	{
		string y = "";
		string space = "";
		string sp = "";
		for (int i = 0; i < n; i++)
		{
			if (i == 0)
			{
				space = new string (' ', (3 * n + 1) - 3 * i);
			}
			else
			{
				space = new string (' ', (3 * n) - 3 * i);
			}

			for (int j = 0; j <= i; j++)
			{
				sp = new string (' ', 5);
				y += comb(i, j).ToString() + sp;
			}

			Console.Write(space + y + " ");
			y = " ";
			Console.WriteLine();
		}
	}
}
;