C# Program to Print Rectangle Pattern
Code Snippet How To C#

C# Program to Print Rectangle Pattern

Mishel Shaji
Mishel Shaji

In this post, we'll learn two different ways to print rectangle patterns in C#.

Method 1

In the first method, we'll use two for loops and one if conditional statement to display a rectangle pattern. Here's the code.

// Height of the rectangle. 
int height = 4;

// The width in 40. So, there will be 40 * in a row.
int width = height * 10;

for (int row = 0; row < height; row++)
{
    for (int column = 0; column < width; column++)
    {
        if(row == 0 || row == height -1 || column == 0 || column == width - 1)
        {
            Console.Write("*");
        }
        else
        {
            Console.Write(" ");
        }
    }
    Console.WriteLine();
}

The output is:

The first for loop loops up to the height of the rectangle and the second for loop loops up to the width of the rectangle.

We have to display the border of the rectangle only on the first row (row 0), the last row (height - 0 because the for loop starts at 0), and the first column of each row (column 0, and the last column (width -1). We used an if-else statement to check this.

Method 2

This method will also give the same output, but instead of using for loop and if-else statement to draw the border of the rectangle, we use string datatype to generate the border of the rectangle.

int height = 4;
int width = height * 10;
string border = new string('*', width);
string content = $"*{new string(' ', width - 2)}*";

Console.WriteLine(border);
for (int row = 0; row < height - 2; row++)
{
    Console.WriteLine(content);
}
Console.WriteLine(border);

In this example, we first created two patterns. One for the top and bottom of the rectangle.

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

and for both sides

*                                                     *

Then we displayed the top side of the rectangle, then the middle section, and then the bottom side of the rectangle.