如何使用带控制台应用程序的c#垂直和水平打印(*)?

时间:2017-12-03 03:44:00

标签: c# console-application

I'm doing odd and even number to print (*) using console application
For ex:
If i'm entering the odd number as 5 then the output should be like:
  *
*****
  *
  *
  *

我的C#代码是:

namespace csharpstar
{
class Program
{
    static void Main(string[] args)
    {
        int num;
        Console.WriteLine("Enter the number:");
        num = int.Parse(Console.ReadLine());

        if (num % 2 == 0)
        {
            Console.Write("The number is Evennumber");
            Console.Read();
        }
        else
        {

            for (int i = 0; i < num; i++)
            {
                    Console.Write("*");
            }

            Console.Read();
        }
    }
}
}

我设法将输出水平但不知道垂直,所以

2 个答案:

答案 0 :(得分:0)

要垂直打印num,您可以执行以下操作:

for(int i = 0; i < num; i++){
    Console.WriteLine("*");
    //Console.Write("*\n"); will also work
}

这将在循环的每次迭代中在新行上输出*

答案 1 :(得分:0)

一个建议是使用PadLeft。

static void Main(string[] args)
    {
        Process();
    }

    static void Process()
    {
        Console.Write("Enter a number: ");
        int.TryParse(Console.ReadLine(), out int num);
        Print(num);
    }

    static void Print(int num)
    {
        if (num % 2 == 0)
        {
            Console.WriteLine(string.Empty.PadLeft(num, '*'));
        }
        else
        {

            for (int i = 0; i < num; i++)
            {
                Console.WriteLine("*");
            }

        }

        Process();
    }
}

或者像这样:

class Program
{
    static void Main(string[] args)
    {
        Process();
    }

    static void Process()
    {
        Console.Write("Enter a number: ");
        int.TryParse(Console.ReadLine(), out int num);
        Print(num);
    }

    static void Print(int num)
    {
        for (int i = 1; i <= num; i++)
        {
            if (i % 2 == 0)
            {
                Console.WriteLine(string.Empty.PadLeft(num, '*'));
            }
            else
            {
                Console.WriteLine("  *  ");
            }
        }

        Process();
    }
}

所以:

    class Program
{
    static void Main(string[] args)
    {
        Process();
    }

    static void Process()
    {
        Console.Write("Enter a number: ");
        int.TryParse(Console.ReadLine(), out int num);
        Print(num);
    }

    static void Print(int num)
    {
        for (int i = 1; i <= num; i++)
        {
            if ((i % 2 == 0) && i == 2)
            {
                Console.WriteLine(string.Empty.PadLeft(num, '*'));
            }
            else
            {
                Console.WriteLine("  *  ");
            }
        }

        Process();
    }
}