How to display numbers in the form of Triangle using C#?

CsharpProgrammingServer Side Programming

To display numbers in the form of Triangle, firstly consider a two dimensional array.

int[,] a = new int[5, 5];

For a triangle, you need to consider spaces as shown below −

1
1 1
1 2 1
1 3 3 1

Then loop through to set the triangle with 1s on the left and right as in the following code −

Example

 Live Demo

using System;

class Demo {
   public static void Main() {
      // two dimensional array
      int[,] a = new int[5, 5];

      for (int i = 0; i < 5; i++) {
         for (int k = 7; k > i; k--) {
            // prints spaces
            Console.Write(" ");
         }

         // loop to print the triangle
         for (int j = 0; j < i; j++) {
            if (j == 0 || i == j) {
               a[i, j] = 1;
            } else {
               a[i, j] = a[i - 1, j] + a[i - 1, j - 1];
            }
            Console.Write(a[i, j] + " ");
         }
         Console.WriteLine();

      }
      Console.ReadLine();
   }
}

Output

1
1 1
1 2 1
1 3 3 1
raja
Published on 09-Aug-2018 07:42:38
Advertisements