Exercise
Function Writerectangle
Objective
Write a C# function WriteRectangle to display a (filled) rectangle on the screen, with the width and height indicated as parameters, using asterisks. Complete the test program with a Main function:
WriteRectangle(4,3);
should display
****
****
****
Create also a function WriteHollowRectangle to display only the border of the rectangle:
WriteHollowRectangle(3,4);
should display
***
* *
* *
***
Write Your C# Exercise
C# Exercise Example
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Function to display a filled rectangle
public static void WriteRectangle(int width, int height)
{
// Loop through each row
for (int i = 0; i < height; i++)
{
// Loop through each column and print an asterisk
for (int j = 0; j < width; j++)
{
Console.Write("*"); // Print an asterisk
}
// Move to the next line after each row
Console.WriteLine();
}
}
// Function to display a hollow rectangle (border only)
public static void WriteHollowRectangle(int width, int height)
{
// Loop through each row
for (int i = 0; i < height; i++)
{
// Loop through each column in the row
for (int j = 0; j < width; j++)
{
// Check if we are at the border of the rectangle (first/last row or column)
if (i == 0 || i == height - 1 || j == 0 || j == width - 1)
{
Console.Write("*"); // Print an asterisk at the border
}
else
{
Console.Write(" "); // Print a space for the hollow part
}
}
// Move to the next line after each row
Console.WriteLine();
}
}
// Main function to test the WriteRectangle and WriteHollowRectangle functions
public static void Main()
{
// Display a filled rectangle with width 4 and height 3
Console.WriteLine("Filled Rectangle:");
WriteRectangle(4, 3);
// Add a line break for better readability
Console.WriteLine();
// Display a hollow rectangle with width 3 and height 4
Console.WriteLine("Hollow Rectangle:");
WriteHollowRectangle(3, 4);
}
}