[英]How to print a reverse stair pattern using a 2D Array in C#
No matter how I change my loop it either prints nothing or prints some kind of upside down triangle.无论我如何更改循环,它要么不打印,要么打印某种倒三角形。 I need it to print like this:
我需要它像这样打印:
An explanation of the logic is appreciated but not necessary
理解逻辑的解释,但不是必需的
static void Main(string[] args)
{
char[,] shape = new char[5, 5];
//Makes Stairs
//for (int i = 0; i < shape.GetLength(0); i++)
//{
// for (int j = 0; j <= i; j++)
// {
// shape[i, j] = '*';
// }
//}
//--------------------------------------------
//*****Makes Reverse Stair: Right now only prints upside down triangle
for (int i = 0; i < shape.GetLength(0); i++)
{
for (int j = 0; j < shape.GetLength(1); j++)
{
if (j >= i)
{
shape[i, j] = '*';
}
}
}
}
}
If you don't assign anything to array item, it keeps its default
value.如果您没有为数组项分配任何内容,它将保持其
default
值。 In case of char
, its default value - \0
- is treated as a string end by Console
.在
char
的情况下,其默认值 - \0
- 被Console
视为字符串结尾。 Let's assign ' '
(space) if we don't assign '*'
:如果我们不分配
'*'
让我们分配' '
(空格):
for (int i = 0; i < shape.GetLength(0); i++)
{
for (int j = 0; j < shape.GetLength(1); j++)
{
if (j >= i)
{
shape[i, j] = '*';
}
else
{
// we don't want '\0' here, but good old space - ' '
shape[i, j] = ' ';
}
}
}
Or put it in a compact form或者放在紧凑的形式
for (int i = 0; i < shape.GetLength(0); i++)
for (int j = 0; j < shape.GetLength(1); j++)
shape[i, j] = j >= i ? '*' : ' ';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.