使用for循环打印图案

本文关键字:打印 循环 for 使用 | 更新日期: 2023-09-27 18:04:36

如何使用for循环打印模式?

图(3(图(4(******************

我试过这个:

static void PrintPattern (int column)
{
    for (int r = 0; r <= column + 1; r++)
    {
        Console.Write("**");
        for (int c = 0; c < r; c++)
        {
            Console.WriteLine(" ");
        }
        Console.WriteLine();
    }
}     

使用for循环打印图案

为了好玩,希望我不会收到太多-1s

int depth = 4;
var rows = Enumerable.Range(0, depth + 1)
                     .Select(v => new string(''t', v) + "**" );
var oneString = string.Join(Environment.NewLine, rows);
Console.WriteLine (oneString);

打印:

**
  **
    **
      **
        **

备注:如果您使用' '作为分隔符,而不是选项卡''t',您将得到下一个结果:

**
 **
  **
   **
    **
    void Main()
    {
        const int rowCount = 10;
        Console.Write("**");
        for (var rowNumber = 0; rowNumber < rowCount - 1; rowNumber++)
        {
            Console.Write("'n ");
            for (var spaceCount = 0; spaceCount < rowNumber; spaceCount++)
            {
                Console.Write(" ");
            }
            Console.Write("**");
        }
    }

工作正常。

对于图3:行=4,
对于图4:行=5

    static void Main(string[] args)
    {
        int lines = 5;
        for (int i = 0; i < lines; i++)
        {
            bool flag = false;
            for (int j = 0; j < lines; j++)
            {
                if (j == i)
                {
                    Console.WriteLine("**");
                    flag = true;
                }
                else
                {
                    if (!flag)
                        Console.Write(" ");
                }
            }
        }
    }

我不懂C#,但我会用Java帮助你。您应该根据需要更改语法(Console.Write==System.out.print&&Console.Writeline==System.out.println(。代码如下:

 static void printPattern(int column){
   int spaceCount = 2;//number of spaces before **, change as needed
   int k;//number of times ** is printed each row, must remain always 1
   for(int i = 0; i < column; i++){
       System.out.println();//starts each row with a new line
       for(int j = 1; j < spaceCount; j++){
           System.out.print(" ");//prints j spaces in each row
        }
        spaceCount++;//increment spacecount each row, so j can also go + 1 
        for(k = 1; k <= 1; k++){
            System.out.print("**");//each row prints ** k times
        }
        k--;//k must remain 1
    }
}

对于图(3(,调用图(4(printPattern(5);printPattern(4);