How to print a reverse stair pattern using a 2D Array in C#

Viewed 36

No matter how I change my loop it either prints nothing or prints some kind of upside down triangle. I need it to print like this: enter image description here An explanation of the logic is appreciated but not necessary

            static void Main(string[] args)
            {
                char[,] shape = new char[5, 5];
    
                
                //Makes Stairs
                //for (int i = 0; i < shape.GetLength(0); i++)
                //{
                //    for (int j = 0; j <= i; j++)
                //    {
                //        shape[i, j] = '*';
                //    }
                //}
                //--------------------------------------------
                
                //*****Makes Reverse Stair: Right now only prints upside down triangle
                for (int i = 0; i < shape.GetLength(0); i++)
                {
                    for (int j = 0; j < shape.GetLength(1); j++)
                    {
                        if (j >= i)
                        {
                            shape[i, j] = '*';
                        }
                    }
                }
    
                
    
        }
    
    }
1 Answers

If you don't assign anything to array item, it keeps its default value. In case of char, its default value - \0 - is treated as a string end by Console. Let's assign ' ' (space) if we don't assign '*':

for (int i = 0; i < shape.GetLength(0); i++)
{
    for (int j = 0; j < shape.GetLength(1); j++)
    {
        if (j >= i)
        {
            shape[i, j] = '*';
        }
        else
        {
            // we don't want '\0' here, but good old space - ' '
            shape[i, j] = ' ';
        }    
    }
}

Or put it in a compact form

for (int i = 0; i < shape.GetLength(0); i++) 
  for (int j = 0; j < shape.GetLength(1); j++) 
    shape[i, j] = j >= i ? '*' : ' ';

Please, fiddle yourself

Related