alabasi alabasi - 1 month ago 8
C# Question

how can I draw a triangle of asterisks using the while statement?

here is the (not working code) and it should print the shape below but its not :

static void Main(string[] args)
{
int i = 1;
int k = 5;
int h = 1;

while (i <= 5)
{
Console.WriteLine("");
while (k > i)
{
Console.Write(" ");
k--;
}
while (h <= i)
{
Console.Write("**");
h++;
}
i++;
}
Console.ReadLine();

}


Screenshot

but when I try to do the same using the while statement the shape gets totally messed up.

any help ?

Answer

You have to declare k and h within the loop:

static void Main(string[] args)
{
    int i = 1;
    while (i <= 5)
    {
        int k = 5;
        int h = 1;

        Console.WriteLine("");
        while (k > i)
        {
            Console.Write(" ");
            k--;
        }
        while (h <= i)
        {
            Console.Write("**");
            h++;
        }
        i++;
    }
    Console.ReadLine();
}

With your current solution, after first outer loop iteration, inner loops do nothing.

Comments