HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Drawing a hollow rectangle of rows and column provided by the console application

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
hollowrowstheapplicationcolumnrectangleprovideddrawingandconsole

Problem

This question was put forward by my senior to draw a hollow rectangle in C#, and with the condition that the rows and column would be specified by the user. I was stuck at first, but tried to code and after several hours I realized how it would be done, and then I accomplished the task.

I would like to share my code, as the beginners may get help out of it, and the experts can also look and propose, if they know any other alternative solution which would be composed of less code.

class Program
{
    static void Main(string[] args)
    {
        int arg1;
        int arg2;
        arg1 =Convert.ToInt16(Console.ReadLine());
        Console.ReadLine();
        arg2 = Convert.ToInt16(Console.ReadLine());
       // Console.WriteLine(arg1 + " " + arg2);
        for (int row = 1; row <= arg1; row++)
        {

            if (row == 1 || row == arg1)
            {
                for (int col = 1; col <= arg2; col++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }

            if (row < arg1 && row < arg1-1)
            {
                Console.Write("*");
                for (int i = 0; i < arg2-2; i++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                    Console.WriteLine();
            }

        }
        Console.ReadKey();
       // Console.ReadKey();
    }
}

Solution

static void DrawLine(int w, char ends, char mids)
    {
        Console.Write(ends);
        for (int i = 1 ; i < w-1 ; ++i)
            Console.Write(mids);
        Console.WriteLine(ends);
    }

    static void DrawBox(int w, int h)
    {
        DrawLine(w, '*', '*');
        for (int i = 1; i < h-1; ++i)
            DrawLine(w, '*', ' ');
        DrawLine(w, '*', '*');
    }

    static void Main()
    {
        DrawBox(10, 10);
    }

Code Snippets

static void DrawLine(int w, char ends, char mids)
    {
        Console.Write(ends);
        for (int i = 1 ; i < w-1 ; ++i)
            Console.Write(mids);
        Console.WriteLine(ends);
    }

    static void DrawBox(int w, int h)
    {
        DrawLine(w, '*', '*');
        for (int i = 1; i < h-1; ++i)
            DrawLine(w, '*', ' ');
        DrawLine(w, '*', '*');
    }

    static void Main()
    {
        DrawBox(10, 10);
    }

Context

StackExchange Code Review Q#23298, answer score: 5

Revisions (0)

No revisions yet.