How to print Hollow Square Pattern in C# - Step by Step Examples
How to print Hollow Square Pattern in C# ?
Answer
To print a Hollow Square Pattern in C#, you can use nested loops. The outer loop controls the rows, and the inner loop controls the columns. Conditions are used to determine whether to print stars or spaces for the pattern.
✐ Examples
1 Print Hollow Square Pattern
In this example,
- We define a function named
PrintHollowSquare
that takes the side lengthn
as a parameter. - We use two nested
for
loops, one for rows and one for columns, to iterate through each cell of the square. - Within the loops, we use conditions to check if we are at the border or inside the square, printing stars (
*
) for the border and spaces ( - Finally, we call
PrintHollowSquare
with the desired side length to print the pattern.
C# Program
using System;
public class Program
{
public static void PrintHollowSquare(int n)
{
for (int i = 0; i < n; i++)
{
string row = "";
for (int j = 0; j < n; j++)
{
if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
{
row += "*";
}
else
{
row += " ";
}
}
Console.WriteLine(row);
}
}
public static void Main()
{
int sideLength = 5;
PrintHollowSquare(sideLength);
}
}
Output
* * * * * * * * * * * * * * * *
Summary
In this tutorial, we learned How to print Hollow Square Pattern in C# language with well detailed examples.
More C# Pattern Printing Tutorials
- How to print Left Half Pyramid Pattern in C# ?
- How to print Right Half Pyramid Pattern in C# ?
- How to print Pyramid Pattern in C# ?
- How to print Rhombus Pattern in C# ?
- How to print Diamond Pattern in C# ?
- How to print Hour Glass Pattern in C# ?
- How to print Hollow Square Pattern in C# ?
- How to print Hollow Pyramid Pattern in C# ?
- How to print Hollow Inverted Pyramid Pattern in C# ?
- How to print Hollow Diamond Pattern in C# ?
- How to print Floyd's Trianlge Pattern in C# ?
- How to print Pascal's Triangle Pattern in C# ?