Advertisement
LStoyanov

Pascal's Triangle

Jan 22nd, 2013
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.25 KB | None | 0 0
  1. class PascalTriangle
  2. {
  3.       static void Main()
  4.       {
  5.         Console.WriteLine("Enter desired number N:");
  6.             int height = int.Parse(Console.WriteLine());
  7.         // const int height = 12;
  8.  
  9.             // Allocate the array in a triangle form
  10.             long[][] triangle = new long[height + 1][];
  11.  
  12.             for (int row = 0; row < height; row++)
  13.             {
  14.                   triangle[row] = new long[row + 1];
  15.             }
  16.  
  17.             // Calculate the Pascal’s triangle
  18.             triangle[0][0] = 1;
  19.             for (int row = 0; row < n – 1; row++)
  20.             {
  21.                   for (int col = 0; col <= row; col++)
  22.                   {
  23.                         triangle[row + 1][col] += triangle[row][col];
  24.                         triangle[row + 1][col + 1] += triangle[row][col];
  25.                   }
  26.             }
  27.  
  28.             // Print the Pascal’s triangle
  29.             for (int row = 0; row < height; row++)
  30.             {
  31.                   Console.Write("".PadLeft((height – row) * 2));
  32.                   for (int col = 0; col <= row; col++)
  33.                   {
  34.                         Console.Write("{0,3} ", triangle[row][col]);
  35.                   }
  36.                   Console.WriteLine();
  37.             }
  38.       }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement