Home > Blockchain >  Hollow Square Inside Hollow Square C#
Hollow Square Inside Hollow Square C#

Time:11-16

Hello is it possible to create this kind of patter using console c#?

Input 1: 5

Input 2 :3

Expected Output:

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

Here the top-left of the 5x5 box overlaps with the top-left of the 3x3 box.

I already tried to recreate this patter but i ended up with just whole square with cross inside

Example of my code below:

int num1,num2, i, j;

Console.WriteLine("Input 1");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Input 2");
num2 = Convert.ToInt32(Console.ReadLine());

for(i = 0;i < num1;i  )
{
    for(j = 0;j < num1;j  )
    {
        if(i == 0 || i == num1 - 1)
        {
            Console.Write(" * ");
        }
        else if(j == 0 || j == num1 - 1)
        {
            Console.Write(" * ");
        }else if (j == num2 -1 || i == num2 -1){
            Console.Write(" * ");
        }
        else
        {
            Console.Write("   "); // space is printed ..
        }
    }
    Console.WriteLine("");
}
Console.ReadLine();

Input 1: 5

Input 2: 3

Output:

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

CodePudding user response:

The reason you're seeing the output you are is that you are also considering values beyond the edges of box 2 as being within the box (along edge lines).

enter image description here

That is to say that your intention is to draw the black lines and the blue lines, but you're continuing the vertical line down (red) and the horizontal line across (red). In these situations, you need to restrict the line vertically or horizontally to ensure you don't extend it too far.

I would create two flags for each of the boxes:

bool borderOfOuterBox = 
            i == 0 // top
            || j == 0 // left side
            || i == (num1 - 1) // bottom
            || j == (num1 - 1); // right side

bool borderOfInnerBox = 
            i == 0 // top
            || j == 0 // left side
            || (i == (num2 - 1) && j < num2) // bottom (note j is within the bounds of num2)
            || (j == (num2 - 1) && i < num2); // right side (not i is within the bounds of num2)

Then the whole check for writing becomes this:

bool borderOfOuterBox = i == 0 || j == 0 || i == (num1 - 1) || j == (num1 - 1);
bool borderOfInnerBox = i == 0 || j == 0 || (i == (num2 - 1) && j < num2) || (j == (num2 - 1) && i < num2);
if (borderOfOuterBox || borderOfInnerBox)
{
    Console.Write(" * ");
}
else
{
    Console.Write("   "); // space is printed ..
}
  •  Tags:  
  • c#
  • Related