patterncsharpMinor
Program to print a triangle of numbers
Viewed 0 times
trianglenumbersprintprogram
Problem
I want to print the following triangle:
I tried to do but I cannot avoid two
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1I tried to do but I cannot avoid two
for loops. Is it possible to achieve the result in a single for loop?static void printtriangle()
{
for (int i = 1; i = 0; --k)
{
for (int j = 1; j <= k; j++)
{
Console.Write("" + (k));
}
Console.WriteLine("");
}
}Solution
You can do it with one loop that goes from a negative number to a positive, and create a string from a range calculated from the number:
That is of course actually two loops, the
int max = 5;
for (int i = 1 - max; i < max; i++) {
Console.WriteLine(String.Join(" ", Enumerable.Range(1, max - Math.Abs(i))));
}That is of course actually two loops, the
Range method will create numbers that the Join method loops through.Code Snippets
int max = 5;
for (int i = 1 - max; i < max; i++) {
Console.WriteLine(String.Join(" ", Enumerable.Range(1, max - Math.Abs(i))));
}Context
StackExchange Code Review Q#79005, answer score: 4
Revisions (0)
No revisions yet.