使用for循环打印模式

时间:2013-03-18 17:06:43

标签: c# for-loop console-application

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

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

4 个答案:

答案 0 :(得分:2)

取笑,希望我不会收到太多-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',则会获得下一个结果:

**
 **
  **
   **
    **

答案 1 :(得分:1)

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

答案 2 :(得分:0)

工作得很好。 。

  

表示图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(" ");
                }
            }
        }

    }

答案 3 :(得分:0)

我不知道C#,但我会用Java帮助你。您应该根据需要更改语法(Console.Write == System.out.print&amp;&amp; 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),请调用printPattern(4);图(4)printPattern(5);