5
\$\begingroup\$

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 <= 5; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            Console.Write("" + (j));

        }
        Console.WriteLine("");

    }


        for (int k = 4; k >= 0; --k)
        {

            for (int j = 1; j <= k; j++)
            {
                Console.Write("" + (k));

            }
            Console.WriteLine("");
         }

    }
\$\endgroup\$
  • 3
    \$\begingroup\$ Why would you want it to be done in a single for-loop? \$\endgroup\$ – Simon Forsberg Jan 29 '15 at 18:35
  • 4
    \$\begingroup\$ By the way, technically you have four for-loops right now. What do you mean by one for-loop? \$\endgroup\$ – Simon Forsberg Jan 29 '15 at 18:36
  • \$\begingroup\$ I am using four for loops. I am trying to finish the work within two loops so as to reduce the loops and increase the performance of the code. I mean increasing execution speed and reducing the overheads associated of loop \$\endgroup\$ – BSG Jan 29 '15 at 18:49
  • \$\begingroup\$ In the above code I have kept the maximum limit of triangle to 5. What if I increase it to 1000?. Will there be drop in performance due to nested loops? \$\endgroup\$ – BSG Jan 29 '15 at 19:25
  • 1
    \$\begingroup\$ Perforance wise, the looping is irrelevant. Most of the time will be spent writing the characters to the console. \$\endgroup\$ – Guffa Jan 29 '15 at 21:36
4
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

One way to do this is with a string of values separated by a space. Then printout a substring of that according to the loop variable:

static void PrintTri(int limit)
{
    if(limit > 1)
    {
        string temp = "";
        for (int i = 1; i <= limit; i++)
        {
            temp += i.ToString() + " ";
            Console.WriteLine(temp.Substring(0, i * 2));
        }
        for(int i = limit - 1; i >=0; i--)
        {
            Console.WriteLine(temp.Substring(0, i * 2));
        }
    }            
}

As for performance, building new strings against using 2 loops will need to be tested.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.