views:

90

answers:

5

A colleague ask me to print a triangle (of any shape) using a single variable and in a single loop. I do it this way:

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Triangle
{
    class Program
    {
        static void Main(string[] args)
        {

            var triangle = "*";
            do { Console.WriteLine(triangle); }
            while ((triangle += "*").Length < 10);

            Console.ReadLine();
        }
    }
}

I hope there must be a better way of doing this. You know one?

EDIT:

Tim ask me how about print a triangle without using variable and loop. Ouch! I thought and still thinking :) you know how it can be done?

+1  A: 

I like your solution, why do you need a better way?

Personally, I'd have gone with a while loop instead:

        var triangle = "";
        while ((triangle += "*").Length < 10)
            Console.WriteLine(triangle);

But that doesn't change much.

Stephen
Thats much better, Setephen :) Thanks.
Ramiz Uddin
+1  A: 

Use Recursion to eliminate loops - you still need a variable.

OTTOMH (plus haven't coded C# in a loooooooong time)

bool PrintLine(int NumStars)
{
 Console.WriteLine(space(NumStars).Replace (" ", "*"));
 if (NumStars < 20)
  PrintLine (NumStars);
}
Raj More
+2  A: 

Do parameters count as variables?

Console.WriteLine(
    Enumerable.Range(2, 9)
              .Aggregate("*", (s, i) => s + Environment.NewLine + new string('*', i)));
Tim Robinson
This absolutely fine, dude :)
Ramiz Uddin
A: 
Process.Start("http://www.google.com/images?q=triangle");
Tim Robinson
A: 

No loop, no variable (you get the idea)

Console.WriteLine("*");
Console.WriteLine("**");
Console.WriteLine("***");
Console.WriteLine("****");
Console.WriteLine("*****");

Meets the requirements. ;)

Ralph Rickenbach
you live in a very smart world.
Ramiz Uddin