Search code examples
c#for-loopcmdconsoleconsole.writeline

why does the first column remain empty on console window in c#


I'm running a simple code to print numbers from 100 to 1:

for (int i = 100; i > 0; i--)
{
   Console.Write(i + "\t");
}

in the console window the first row is printed fine. but the other rows don't start from the beginning of the line.(the column under 100 remains empty)

here's a picture of what I'm getting as a result. how can I fix this? my result


Solution

  • If you want a simple example about how to check the console size, the Console.WindowWidth is a good starting point. Then you only have to count how many columns can be fitted (numCols), how many pieces of data you wrote (n) and you are ready to go.

    // Current window width in characters
    int w = Console.WindowWidth;
    int tabSize = 8;
    int numCols = w / tabSize;
    
    for (int i = 100, n = 0; i > 0; i--, n++)
    {
        if (n == 0)
        {
            // First element, do nothing
        }
        else if (n % numCols == 0)
        {
            // Written numCols elements, go to new line
            Console.WriteLine();
        }
        else
        {
            // Simply add tab
            Console.Write("\t");
        }
    
        Console.Write(i);
    }
    
    Console.WriteLine();