Asterisk tree algorithm *

Asked

Viewed 312 times

2

I have a problem in an activity, the activity would be to make an asterisk tree of the type:

   *
  ***
 *****

but with my code

for (int i = 0; i <= 5 ; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                Console.Write("*");

            }
            Console.WriteLine();
        }

the result is something like this

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

someone can help me?

  • Print the appropriate amount of spaces before printing the '*'.

  • 1

    Check this out: https://answall.com/q/136861/101

2 answers

2

I made one simpler yet, which only uses four lines of code.

const int linhas = 5;

for(int i = 0; i <= linhas*2; i++)
    if(i % 2 != 0)
        Console.WriteLine(new string(' ', (linhas*2 - i) /2 ) + new string('*', i));

See working on .NET Fiddle.

0


I managed to do it in a way that got better, your answer only worked with the value 3. in that code, I can put any value on the X that will work

var x = 10;

        for (int i = 0; i <= x; i++)
        {
            for (int j = x; j > i; j--)
            {
                Console.Write(" ");
            }
            for (int j = 0; j <= i; j++)
            {
                Console.Write("*");
            }
            for (int j = 0; j < i; j++)
            {
                Console.Write("*");
            }
            Console.WriteLine();
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.