Hollow Square Border of 1s in C#

What You’ll Learn
How to print a hollow square using nested loops, by printing 1 only on the border and spaces in the middle.
This pattern is a classic way to learn row/column boundary checks in C#.
⭐ Pattern Output
For a 5 x 5 grid, the pattern looks like this:
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 1Complete C# Program
Print 1 when the current cell is on the boundary (first/last row or column); otherwise print spaces.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 5; j++)
{
if (i == 1 || i == 5 || j == 1 || j == 5)
Console.Write("1 ");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Two loops create a grid
The outer loop controls rows (i), and the inner loop controls columns (j).
Border check
If we are in row 1/5 or column 1/5, we print "1 ".
Inside stays blank
For inner cells, we print spaces so the square is hollow.
Variation — User Input Size (NxN)
Let the user choose the square size and print the same hollow border pattern.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int size;
Console.Write("Enter square size: ");
if (!int.TryParse(Console.ReadLine(), out size) || size <= 1)
{
Console.WriteLine("Please enter an integer greater than 1.");
return;
}
for (int i = 1; i <= size; i++)
{
for (int j = 1; j <= size; j++)
{
if (i == 1 || i == size || j == 1 || j == size)
Console.Write("1 ");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Print
0inside instead of spaces to make a filled pattern - Use a different border value (like
*or#) - Add a space after every print to keep columns aligned
Avoid
- Using size 1 (a border-only hollow square needs at least 2)
- Forgetting the newline after each row
Key Takeaways
Nested loops iterate through a 2D grid.
Border cells satisfy i==1, i==size, j==1, or j==size.
Inner cells print spaces to keep the square hollow.
Time complexity is O(n²) for an \(n \times n\) grid.
Explore More C# Number Patterns!
Border patterns teach you how to think in terms of grid coordinates and boundaries.
Boundary checks like i == 1 || i == size are also used to print rectangle borders, frames, and outlines in many console pattern problems.
12 people found this page helpful
