HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Program to print a triangle of numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
trianglenumbersprintprogram

Problem

I want to print the following triangle:

1
1  2
1  2  3
1  2  3  4
1  2  3  4  5
1  2  3  4
1  2  3
1  2
1


I 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:

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.