I have a requirement to draw n number of squares with side length m in the following format:
Example: m=5;n=2;
Expected output
* * * * * * * *
* * *
* * *
* * *
* * * * * * * *
This is the method I wrote, but it isn’t working as it should be:
Console.Write("Enter the value of m (side length): ");
int m = int.Parse(Console.ReadLine());
Console.Write("Enter the value of n (number of squares): ");
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
for (int k = 0; k < m; k++)
{
Console.Write("* ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Sasho is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Before start coding, start shape analysis, what is the dimension (width and height) of the output Shape as function of (m, n)
the height is easy to determine, is just m
so lets determine the width of the shape
the following pattern is repeated n times
****
*
*
*
****
every single pattern width is (m-1)
so the result width is (m-1)n
and we need to add this shape to the column of asterisks at the beginning to make it complete square
*
*
*
*
*
so the total width is (m-1)n+1
simplify it mn-n+1
your shape is consisted of asterisks *
and spaces
and we need to know where to put asterisk and where to put space
*********
*********
the first horizontal line and last one, all of them are asterisks
the column is repeated every (m-1) time, we can use modulus operator to say it repeated
the rest of the shape should be space
Console.Write("Enter the value of m (side length): ");
int m = int.Parse(Console.ReadLine());
Console.Write("Enter the value of n (number of squares): ");
int n = int.Parse(Console.ReadLine());
var width = m * n - n + 1;
var height = m;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (y == 0 || y == height - 1)
Console.Write('*');
else if(x%(m-1)==0)
Console.Write('*');
else
Console.Write(' ');
}
Console.WriteLine();
}
1