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

แสดงตัวเลขแบบสามเหลี่ยม (Triangle) ใน C#

การแสดงตัวเลขแบบสามเหลี่ยม (Pascal's Triangle) ใน C#

ใช้ 2D Array คำนวณค่า Pascal's Triangle: แต่ละค่า = ผลรวมของค่าด้านบนซ้ายและบนขวา ขอบซ้าย-ขวา = 1

อัลกอริทึม

  1. สร้าง 2D Array ขนาด [n, n]
  2. Loop แถว (i) 0 ถึง n-1
  3. Loop คอลัมน์ (j) 0 ถึง i
  4. ถ้า j==0 หรือ j==i → ค่า = 1 (ขอบ)
  5. อื่นๆ → arr[i,j] = arr[i-1,j-1] + arr[i-1,j]
  6. Print พร้อม Space เพื่อจัดรูปสามเหลี่ยม

ตัวอย่างโค้ดครบถ้วน


using System;

class Demo
{
    public static void Main()
    {
        int rows = 5;
        int[,] triangle = new int[rows, rows];
        
        for (int i = 0; i < rows; i++)
        {
            // Print leading spaces for triangle shape
            for (int space = rows - i; space > 0; space--)
                Console.Write("  ");
            
            for (int j = 0; j <= i; j++)
            {
                if (j == 0 || j == i)
                    triangle[i, j] = 1; // Edge
                else
                    triangle[i, j] = triangle[i-1, j-1] + triangle[i-1, j]; // Sum of two above
                
                Console.Write($"{triangle[i, j]}   ");
            }
            Console.WriteLine();
        }
        Console.ReadLine();
    }
}

ผลลัพธ์


          1
        1   1
      1   2   1
    1   3   3   1
  1   4   6   4   1

Variations

Floyd's Triangle (ลำดับตัวเลขต่อเนื่อง)


int num = 1;
for (int i = 1; i <= 5; i++)
{
    for (int j = 1; j <= i; j++)
        Console.Write($"{num++} ");
    Console.WriteLine();
}
/*
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
*/

Right-Angled Triangle (Star Pattern)


for (int i = 1; i <= 5; i++)
{
    for (int j = 1; j <= i; j++)
        Console.Write("* ");
    Console.WriteLine();
}
/*
*
* *
* * *
* * * *
* * * * *
*/

การประยุกต์ใช้

  • Binomial Coefficients (nCr)
  • Combinatorics, Probability
  • Polynomial Expansion (x+y)^n
  • Algorithm Practice (Loops, 2D Arrays)