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.
Logic would be simple:
write *
character as many times as W
, then write new line to start new row - repeat this as many times as H
Putting it into code:
var W = 10;
var H = 10;
for (var i = 0; i < H; i++)
{
for (var j = 0; j < W; j++)
{
Console.Write('*');
}
Console.WriteLine();
}
Using more concise code:
for (var i = 0; i < H; i++)
{
Console.WriteLine(new string('*', W));
}
UPDATE
In order to draw only border with characters:
var W = 10;
var H = 10;
for (var i = 0; i < H; i++)
{
// for bottom and for top borders - print full line
if (i == 0 || i == H - 1)
Console.WriteLine(new string('*', W));
// for other, print just W-2 spaces with * at the edges
else
Console.WriteLine('*' + new string(' ', W - 2) + '*');
}