Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

จะแสดงตัวเลขในรูปของ Triangle โดยใช้ C # ได้อย่างไร?


หากต้องการแสดงตัวเลขในรูปสามเหลี่ยม อันดับแรก ให้พิจารณาอาร์เรย์สองมิติ

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

สำหรับสามเหลี่ยม คุณต้องพิจารณาช่องว่างดังที่แสดงด้านล่าง −

1
1 1
1 2 1
1 3 3 1

จากนั้นวนซ้ำเพื่อกำหนดรูปสามเหลี่ยมด้วย 1s ทางซ้ายและขวาตามรหัสต่อไปนี้ −

ตัวอย่าง

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();
   }
}

ผลลัพธ์

1
1 1
1 2 1
1 3 3 1