C# Program to create Pascal’s Triangle

CsharpProgrammingServer Side Programming

A Pascal’s triangle contains numbers in a triangular form where the edges of the triangle are the number 1 and a number inside the triangle is the sum of the 2 numbers directly above it.

A program that demonstrates the creation of the Pascal’s triangle is given as follows.

Example

 Live Demo

using System;
namespace PascalTriangleDemo {
   class Example {
      public static void Main() {
         int rows = 5, val = 1, blank, i, j;
         Console.WriteLine("Pascal's triangle");
         for(i = 0; i<rows; i++) {
            for(blank = 1; blank <= rows-i; blank++)
            Console.Write(" ");
            for(j = 0; j <= i; j++) {
               if (j == 0||i == 0)
               val = 1;
               else
               val = val*(i-j+1)/j;
               Console.Write(val + " ");
            }
            Console.WriteLine();
         }
      }
   }
}

Output

The output of the above program is as follows.

Pascal's triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Now, let us understand the above program.

The Pascal’s triangle is created using a nested for loop. The outer for loop situates the blanks required for the creation of a row in the triangle and the inner for loop specifies the values that are to be printed to create a Pascal’s triangle. The code snippet for this is given as follows.

for(i = 0; i<rows; i++) {
   for(blank = 1; blank <= rows-i; blank++)
   Console.Write(" ");
   for(j = 0; j <= i; j++) {
      if (j == 0||i == 0)
      val = 1;
      else
      val = val*(i-j+1)/j;
      Console.Write(val + " ");
   }
   Console.WriteLine();
}
raja
Published on 23-Nov-2018 06:02:42
Advertisements