print 1,1 2,1 2 3,1 2 3 4 ...... through c# [closed]
print 1,1 2,1 2 3,1 2 3 4 ...... through c#
Use nested loops. Use the outside to count how many numbers you're going to count this pass and then use the inner loop to actually count through the numbers each time:
for(int i=1; i <= limit; i++)
{
for(int a=1; a <= i; a++)
{
Console.Write(a + " ");
}
Console.Write(", ");
}
P.S. - If this is a homework question rather than sheer curiosity (or a simplified version of a larger problem) please be sure to tag it as such. The answers will give much more explanation rather than simply giving you code.
You can use a nested loop. The outer counts up the limit and prints the comma, the inner loop prints the space separated consecutive numbers. But you should be able to come up with such a solution yourself.
Here is once fancy but unreadable one:
String.Join(",",
Enumerable.Range(1,10)
.Select(i=> String.Join(" ",
Enumerable.Range(1,i)
.Select(j=>j.ToString()))))
The naive solution uses nested loops. You can do it without nested loops:
var sb = new StringBuilder();
int n = 1;
while (true) {
sb.Append(String.Format("{0} ", n));
Console.Write("{0}, ", sb.ToString().TrimEnd());
n++;
}
A very naive and quick solution
for(int i=0;i<N;i++)
{
for (j=0;j<i;j++)
Console.Write(j.ToString()+" ");
Console.WriteLine();
}
for (int i = 1; i < maxNumber; i++)
{
for (int j = 1; j < i+1; j++)
{
Console.Write(j);
Console.Write(',');
}
Console.WriteLine();
}
I thought it was fun trying to achieve this completely in LINQ/method chains, but I only could do it halfway. Any suggestions, on how to get rid of the recursive method?
string GetNumberString(int n)
{
if(n==1)
return "1";
else
return GetNumberString(n-1)+" "+n;
}
void Main()
{
Console.WriteLine(Enumerable.Range(1,10).
Select(n => GetNumberString(n)).Aggregate((a, b) => a+", "+b));
}
int total = 10;
for (int i = 0; i < total; i++)
{
for (int j = 1; j <= i; j++)
{
Debug.WriteLine(j.ToString());
}
}
精彩评论