Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# christmas tree

Tags:

c#

algorithm

I'm novice in C# and cause I request help me to implement this:

        *
        *
       ***
        *
       ***
      *****
        *
       ***
      *****
     ******* 
        *
       ***
      *****
     ******* 
    ********* 

I just had this code:

class Program
{
    static void Main(string[] args)
    {
        AnotherTriangle ob = new AnotherTriangle();
        ob.CreateTriangle();

        Console.ReadLine();
    }
}
class AnotherTriangle
{
    int n;
    string result = "*";
    public void CreateTriangle()
    {
    flag1:
        Console.Write("Please enter number of triangles of your tree: ");
        n = int.Parse(Console.ReadLine());
        Console.WriteLine();
        if (n <= 0)
        {
            Console.WriteLine("Wrong data type\n"); goto flag1;
        }
        string s = "*".PadLeft(n);
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine(s);
            s = s.Substring(1) + "**";
            for (int j = 0; j < n; j++)
            {
                Console.WriteLine(s);
            }
        }
    }
}

At now I have only "tower", not equilateral triangle. Please help.

like image 840
Олег Avatar asked Sep 29 '15 11:09

Олег


1 Answers

Console.WriteLine("Please enter the number of triangles in your tree: ");
int n = int.Parse(Console.ReadLine());

for (int i = 1; i <= n; i++)
{
    for (int j = 0; j < i; j++)
    {
        string branch = new String('*', j);
        Console.WriteLine(branch.PadLeft(n + 3) + "*" + branch);
    }
}

A working example.

like image 59
Dmytro Shevchenko Avatar answered Sep 21 '22 22:09

Dmytro Shevchenko