TheBulgarianWolf

Pascal Triangle

Dec 16th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace jaggedArrays
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             //Pascal triangle
  14.             const int HEIGHT = 12;
  15.             //allocate the array in a triangle form
  16.             long[][] triangle = new long[HEIGHT + 1][];
  17.  
  18.             for (int row = 0; row < HEIGHT; row++)
  19.             {
  20.                 triangle[row] = new long[row + 1];
  21.             }
  22.  
  23.             //calculate the Pascal's triangle
  24.             triangle[0][0] = 1;
  25.             for (int row = 0; row < HEIGHT - 1; row++)
  26.             {
  27.                 for (int col = 0; col <= row; col++)
  28.                 {
  29.                     triangle[row + 1][col] += triangle[row][col];
  30.                     triangle[row + 1][col + 1] += triangle[row][col];
  31.                 }
  32.             }
  33.  
  34.             //print the Pascal's triangle
  35.             for (int row = 0; row < HEIGHT; row++)
  36.             {
  37.                 Console.Write("".PadLeft((HEIGHT - row) * 2));
  38.                 for(int col = 0;col<= row; col++)
  39.                 {
  40.                     Console.Write("{0,3} ", triangle[row][col]);
  41.                 }
  42.                 Console.WriteLine();
  43.             }
  44.             Console.ReadLine();
  45.         }
  46.     }
  47. }
Add Comment
Please, Sign In to add comment