Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Creating a Square

I’m trying to create an application that inputs a Width and Height to design a square. I’ve gotten the error handling for inputting the numbers for the Width and Height. I find myself writing…

//Integer for Width == W
int W;
//Integer for Height == H
int H;
      if (W == 1 && H == 1)
      {
         Console.WriteLine("*");
      }
      else if (W == 1 && H == 2)
      {
         Console.WriteLine("*\n" +
                           "*");
      }
      else if (W == 1 && H == 3)
      {
         Console.WriteLine("*\n" +
                           "*\n" +
                           "*");
      }
     //~~~~~~~~~~~~~~~~~~~~~~~~~~~
      else if (W == 1 && H == 20)
      {
         Console.WriteLine("*\n" +
                           "*\n" +
                          //~~~~~~~
     //For readability 20th"*");

Also, assuming I’d do (else if) another 396 more times to satisfy the variances (20 * 20 = 400) 400 possibilities to build this square.

I’m asking if there is any looping methods that could help me reduce the code I need to complete making my square out of Console.WriteLine("*").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if(W == 1 && H == 1) ~~~ else(W == 20 && H == 20)

Or am I stuck writing the 400 possible instances of the width and height of my square?

The desired result for the display

 ****
 *  *
 *  *
 ****

Thanks for your time and consideration of my question.

>Solution :

You can achieve it via nested loops and a bit of formatting while outputting * to console.

var width = 50;
var height = 50;

for (var x = 0; x < height; x++)
{
    for (var y = 0; y < width; y++)
    {
        if (x == 0 || y == 0 || x == (height - 1) || y == (width - 1))
        {
            Console.Write('*');
        }

        if (x > 0 && x < (height - 1) && y > 0 && y < (width - 1))
        {
            Console.Write(' ');
        }
    }

    Console.WriteLine();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading