Hollow Square Border of 1s in C#

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Condition

What You’ll Learn

The hollow square border prints 1s on the edges and spaces inside a 5 × 5 grid — a natural step after Program 41’s square-number pyramid. This tutorial covers nested loops with border conditions, a live preview, worked C# examples, edge cases, and complexity.

Shape Rule

Border only

Row 1 and row 5 are all 1s; middle rows have 1 at both ends and spaces between.

Outer Loop

i = 1..size

for (i = 1; i <= size; i++) walks each row of the grid.

Inner Loop

j = 1..size

for (j = 1; j <= size; j++) walks each column within the current row.

Border Check

i or j on edge

i == 1 || i == size || j == 1 || j == size prints 1; else print spaces.

Live Preview

3–9 size

Pick a square size and draw the hollow border in the browser.

O(n²)

Complexity

Each cell visited once — prints for n × n; extra memory stays O(1).

Introduction

A hollow square border prints 1 only on the first/last row and first/last column; interior cells are blank spaces. With size = 5, the output is a 5 × 5 frame of 1s with a hollow center.

In C# the outer loop runs i = 1..size, the inner loop runs j = 1..size, and a border condition picks "1 " or " " per cell.

Why it matters?

It teaches grid coordinates and boundary checks — a key step after Program 41’s formatted pyramid.

Key Highlights

Border cells

First/last row or column.

Hollow inside

Interior prints " ".

vs Program 41

Program 41 prints squares in a pyramid; Program 42 prints a hollow grid.

Series Foundation

Follow Program 41; continue to Program 43 next.

In short: nested loops over i, j, border check prints "1 ", else " ", then WriteLine().

📝 Problem & Approach

Given a square size (e.g. 5), print a hollow border of 1s — edges filled, interior blank.

C#
// size = 5
//1 1 1 1 1
//1       1
//1       1
//1       1
//1 1 1 1 1

Inputs & Outputs

ItemTypeDescription
sizeintSide length of the square grid (e.g. 5 for 5×5).
iintOuter loop — current row index (1 to size).
jintInner loop — current column index (1 to size).

Minimal workflow

Pseudocode
for i from 1 to size:
    for j from 1 to size:
        if i or j is on border:
            print "1 "
        else:
            print "  "
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + condition1 1 1 1 1, hollow centerLearning and interviews
User-input sizeint.TryParse(...)Flexible N×N grids
Custom border char"* " instead of "1 "Alternate border symbol

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= size; i++)
Walk columnsfor (j = 1; j <= size; j++)
Border checkif (i == 1 || i == size || j == 1 || j == size)
Print borderConsole.Write("1 ");
Print interiorConsole.Write(" ");
Program 41 contrastSquare-number pyramid with m*m — not a hollow grid

📋 Fixed Size vs User Input vs Custom Border

Same hollow square — different ways to control size and border character.

Outer loop
i = 1..size

Rows of the grid

Inner loop
j = 1..size

Columns per row

Border
i/j on edge

Condition per cell

Alignment
"1 " / "  "

Two chars per cell

Context

When This Pattern Shows Up

Reach for this pattern when teaching 2D grids, boundary conditions, and hollow shapes.

  1. Post Program 41 exercise

    Natural follow-up after Program 41 — same nested loops but adds per-cell border logic.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with ReadLine for a flexible row count.

  4. Gateway to variants

    Compare Program 41 (square pyramid) and Program 43 (next in series) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a square size between 3 and 9 and draw the hollow border in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C# programs — fixed rows, user input, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print a 5×5 hollow square border with nested loops and a border condition.

Example 1 — Fixed size = 5

Hard-coded grid size — ideal for first demos and screenshots.

C#
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

When i = 1 or i = 5, every cell is on the border — all 1s. When i = 3 and j = 3, neither row nor column is on the edge — prints spaces.

📈 User Input

Read the square size from the console instead of hard-coding 5.

Example 2 — User Input Size

Read size from the console with safe parsing.

C#
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();
            }
        }
    }
}

How It Works

Same inner-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Custom Border

Swap 1 for * on the border — same condition, different character.

Example 3 — Asterisk Border

Keep size = 5 but print * on the border instead of 1.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int size = 5;

            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("* ");
                    else
                        Console.Write("  ");
                }
                Console.WriteLine();
            }
        }
    }
}

How It Works

Only the border character changes — "* " instead of "1 ". The border condition and interior spaces stay the same as Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

using System; brings in Console. Set loop variables i, j for a 5 × 5 grid.

Setup
2

Nested loops build grid

for (i = 1; i <= size; i++) and for (j = 1; j <= size; j++) visit every cell in the grid.

Grid
3

Border check

if (i == 1 || i == size || j == 1 || j == size) — true on any edge cell.

Condition
4

Print border or space

Border cells print "1 "; interior cells print " " to keep columns aligned.

Output
5

New line

Console.WriteLine() ends each row after the inner loop finishes.

Break
=

Hollow square complete

Every cell visited once — O(n²) time for n × n, O(1) extra memory.

🔎 Worked Walkthrough — size = 5, row i = 3

Trace each column j on row 3 — which cells are border vs interior.

jOn border?Prints
1Yes (j == 1)1
2No
3No
4No
5Yes (j == 5)1

Row 3 output: 1 1 — border cells at both ends, spaces in between. Total cells = size² = 25 for a 5×5 grid.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change border to * or # — see Example 3.

2. Pattern Series Base

Foundation for rectangles, diamonds, frames, and filled variants.

Example: continue to Program 43 for the next pattern in the series.

3. Console Formatting Drills

Practice Write vs WriteLine without complex math.

Example: put WriteLine inside the inner loop by mistake.

4. Spaced Output

Add a different border character once the two-loop structure works.

Example: use "* " instead of "1 " on the border.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count border cells for size = 5 — total grid cells = 25, border = 16.

6. Input Validation Labs

Pair the pattern with TryParse and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner C# courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Change border char, fill interior with 0, or scale to rectangles with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i = 3 and each j on paper before coding — watch how corner cells match two border conditions.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Use the size Variable

    Never hard-code 5 in the border check — use size everywhere.

  2. 2. Prefer TryParse

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep WriteLine Outside

    Only call WriteLine() after the inner loop finishes the row.

  4. 4. Match Cell Width

    Border uses "1 " (2 chars); interior must use " " (2 spaces) for alignment.

  5. 5. Dry-Run size = 3

    Trace i = 1, 2, 3 and each j on paper before coding the full size = 5 demo.

Pro Tip: if the output is a vertical list of single squares per line, you almost certainly put WriteLine inside the print loop.

Common Pitfalls

Mistakes that commonly break hollow square border patterns.

  1. 1. WriteLine Inside the Inner Loop

    Each cell lands on its own line — you get a column, not a square.

    → Use Write("1 ") or Write(" ") per cell; WriteLine only after the inner loop.

  2. 2. Hard-Coded Size in Condition

    Using i == 5 in the check breaks when size changes to 7 or 10.

    → Always use size variable: i == size || j == size.

  3. 3. Mismatched Cell Width

    Border prints "1 " but interior prints a single space — columns drift apart.

    → Use two spaces for interior: Console.Write(" ") to match "1 " width.

  4. 4. Size Too Small

    size = 1 prints a single 1 with no hollow interior; size = 2 is the thinnest frame.

    → Validate size >= 2 for interactive programs expecting a hollow square.

  5. 5. Blind Convert.ToInt32

    Letters or empty input throw FormatException.

    → Prefer int.TryParse and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Size = 1

Output is just 1 on one line — no hollow interior.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Size = 2

Thinnest hollow frame — four border cells forming a square ring.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Large row count

Each cell visited once — total work grows as for n × n grid.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Square pyramid

  • Review Program 41’s m*m pyramid
  • Compare with Program 41

2. Filled square

  • Print 1 in every cell — no border check
  • Same nested loops, no else branch

3. Next in series

  • Continue with Program 43
  • Build on grid boundary logic

4. Asterisk border

  • Use "* " instead of "1 "
  • Same condition, different character

Notes

  • Border rule. Print 1 when i == 1 || i == size || j == 1 || j == size; else print two spaces.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • A size × size grid has size² cells — border cells = 4*size - 4 for size >= 2.

Quick Takeaway: nested loops over i, j, border check prints "1 ", else " ", then WriteLine().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The hollow square border is a compact nested-loop lesson: visit every cell in an n × n grid and use a border condition to print 1 or spaces. Master the fixed-size version, then try user input and a custom border character.

Practice the three examples above, then continue to Program 43 for the next pattern in the series.

Border = first/last row or column — keep cell width consistent ("1 " vs " ") and validate size when reading input.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= size; i++) and for (j = 1; j <= size; j++)
  • Border: if (i == 1 || i == size || j == 1 || j == size)
  • Print "1 " on border, " " inside
  • Validate size ≥ 2 for interactive programs
  • Prefer int.TryParse over bare Convert.ToInt32

❌ Don’t

  • Call WriteLine inside the inner cell loop
  • Hard-code 5 in the border condition
  • Use single space for interior when border uses two chars
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this hollow square border

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Rows i = 1..size

Code
03

Inner loop

Columns j = 1..size

Code
04

Condition

i/j on edge

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A hollow square prints characters only on the border (first/last row and first/last column) and leaves the inside blank with spaces.
It checks if i is 1 or size, or if j is 1 or size. If any condition is true, it prints 1; otherwise it prints spaces.
Use a size variable and loop from 1 to size for both i and j. Update the border check to use size instead of 5 — see Example 2.
Each border cell uses "1 " (digit plus space). Interior cells use " " so columns stay aligned in the console.
Size 2 gives a thin border frame. Size 1 prints a single 1 with no hollow interior.
Program 41 prints a centered pyramid of perfect squares. Program 42 prints a hollow square grid using border conditions.
Replace "1 " with "* " or "# " in the if branch — see Example 3.
O(n²) for an n×n grid because each cell is visited once.
Prefer int.TryParse(Console.ReadLine(), out size) and validate size >= 2 for a meaningful hollow frame.

Did you Know? 🔊

Print 1 when i == 1, i == size, j == 1, or j == size; otherwise print spaces. A size × size grid visits cells — total prints = .

Continue to Program 43

Move on to the next pattern in the C# number-pattern series.

Program 43 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful