简体   繁体   中英

Print a star (*) right triangle in C#

I have already done this with a nested for loop but, I also want to know how to do this with a while loop. I already have this

 int j = 10;
     int k = 0;
     while (j > 0)
     {
        if (k <= j)
        {
           Console.Write("* ");
           Console.WriteLine();
        }
        j--;
     } Console.WriteLine();

and it prints out a line of stars(*). I know the inner loop has to refer to the outer loop but I'm not sure how to do this in a while statement.

Since this has already been done using nested for-loops, then conversion to while-loops is straight forward. (If using the same algorithm , 2 for-loops will result in 2 while-loops, not 1.)

This for-loop :

for (initializer; condition; iterator) {
    body;
}

Is equivalent to this while-loop:

initializer;
while (condition) {
    body;
    iterator;
}

Nit: There is actually a breaking change in C# 5 with respect to the variable lifetimes making the above ever-so-not-quite-identical (in C# 5+), but that is another topic for a language specification not yet finalized and only affects variables bound in closures.

for loops are trivially interchangeable with while loops.

// Height and width of the triangle
var h = 8;
var w = 30;

// The iterator variables
var y = 1;
var x = 1;

// Print the tip of the triangle
Console.WriteLine("*");

y = 1;
while (y++ <h) {
    // Print the bit of left wall
    Console.Write("*");

    // Calculate length at this y-coordinate
    var l = (int) w*y/h;

    // Print the hypothenus bit
    x = 1;
    while (x++ <l-3) {
            Console.Write(" ");
    }
    Console.WriteLine("*");
}

// Now print the bottom edge
x = 0;
while (x++ <w) {
    Console.Write("*");
}

Output:

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

This does produce something resembling a triangle:

int x = 1;
int j = 10;
int k = 0;
while (j > 0)
{
    if (k <= j)
    {
       Console.Write("* ");
    }
    if (j >= 1)
    {
        int temp = x;
        while (temp >= 0)
        {
            Console.Write(" ");
            temp--;
        }
        x = x + 1;
        Console.Write("*");

     }
       Console.WriteLine();
       j--;
   }
   Console.WriteLine();
   double f = Math.Round(x * 1.5);
   while (f != 0)
   {
      Console.Write("*");
      f--;
   }
 class x
    {
        static void Main(string[] args)
        {
            int i, j;
            for ( i=0;i<10;i++)
            {
                for (j = 0; j < i; j++)
                    Console.Write("*");
                Console.WriteLine();
            }

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM