[英]Nested Loop In C#
I'm doing a simple c# exercise. 我正在做一个简单的C#练习。 Here's the problem: Write a program called SquareBoard that displays the following n×n (n=5) pattern using two nested for-loops.
这是问题所在:编写一个名为SquareBoard的程序,该程序使用两个嵌套的for循环显示以下n×n(n = 5)模式。 Here's my code:
这是我的代码:
Sample output:
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
Here's my code: 这是我的代码:
for (int row = 1; row <=5; row++) {
for (int col = 1;col <row ; col++)
{
Console.Write("#");
}
Console.WriteLine();
}
But it doe's not work .can anyone help me. 但这没有用。任何人都可以帮我。 thank you..
谢谢..
int n = 5;
for (int row = 1; row <= n; row++) {
for (int col = 1;col <= n; col++) {
Console.Write("# ");
}
Console.WriteLine();
}
Something like that? 这样的事吗?
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
Console.Write("# ");
}
Console.WriteLine();
}
This code: 这段代码:
col <row
is causing you problems. 给您带来麻烦。
Change it to: 更改为:
col <=5
and it should work 它应该工作
I think this should work: 我认为这应该工作:
int n = 5;
for (int row = 1; row <=n; row++)
{
string rowContent = String.Empty;
for (int col = 1;col <=n; col++)
{
rowContent += "# ";
}
Console.WriteLine(rowContent);
}
Of course you might want to use a StringBuilder
if you are doing this kind of thing a lot. 当然,如果您经常做这种事情,则可能要使用
StringBuilder
。
In the first iteration, you compare col
to row
, and they are both 1. You check if the one is higher than the other, and the second loop never runs. 在第一次迭代中,将
col
与row
进行比较,它们均为1。您检查一个循环是否高于另一个循环,并且第二个循环永远不会运行。 Rewrite like this: 像这样重写:
for (int row = 1; row <=5; row++) {
for (int col = 1;col <= 5 ; col++)
{
Console.Write("#");
}
Console.WriteLine();
}
The second iteration needs to run from 1 to 5 every time. 每次第二次迭代需要运行1到5。
This definitely works: 这绝对有效:
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
Console.Write("# ");
}
Console.Write("\n");
}
for(int i=0; i<5 ; i++)
for(int j=0 ; j <5 ; j++)
Console.Write("#");
Console.WriteLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.