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