Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

In hình kim cương (Diamond) bằng lồng vòng lặp C#

In hình kim cương (diamond) dùng nested loop: n hàng trên (tăng), n-1 hàng dưới (giảm). Mỗi hàng: khoảng trắng + ký tự.

Ví dụ minh họa

using System;

class Program
{
    static void Main()
    {
        PrintDiamond(5, '$');
        Console.WriteLine();
        PrintDiamond(4, '*');
    }
    
    static void PrintDiamond(int rows, char symbol = '*')
    {
        // Phần trên (kể cả hàng giữa)
        for (int i = 1; i <= rows; i++)
        {
            // Khoảng trắng: rows - i
            Console.Write(new string(' ', rows - i));
            // Ký tự: 2*i - 1
            Console.WriteLine(new string(symbol, 2 * i - 1));
        }
        
        // Phần dưới (không kể hàng giữa)
        for (int i = rows - 1; i >= 1; i--)
        {
            Console.Write(new string(' ', rows - i));
            Console.WriteLine(new string(symbol, 2 * i - 1));
        }
    }
}

Kết quả đầu ra (rows=5)

    $
   $$$
  $$$$$
 $$$$$$$
$$$$$$$$$
 $$$$$$$
  $$$$$
   $$$
    $

Giải thích thuật toán

  • Hàng i (1-indexed): spaces = rows - i, symbols = 2*i - 1
  • Hàng giữa (i=rows): spaces=0, symbols=2*rows-1 (rộng nhất)
  • Phần dưới: lặp ngược từ rows-1 về 1

Biến thể: Hollow Diamond (kim cương rỗng)

static void PrintHollowDiamond(int rows, char symbol = '*')
{
    // Top
    for (int i = 1; i <= rows; i++)
    {
        Console.Write(new string(' ', rows - i));
        if (i == 1) Console.WriteLine(symbol);
        else Console.WriteLine(symbol + new string(' ', 2*i - 3) + symbol);
    }
    // Bottom
    for (int i = rows - 1; i >= 1; i--)
    {
        Console.Write(new string(' ', rows - i));
        if (i == 1) Console.WriteLine(symbol);
        else Console.WriteLine(symbol + new string(' ', 2*i - 3) + symbol);
    }
}