-2

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

estrella
  • 33
  • 5
  • 4
    There is nothing that will make the Console go to a new line, so what you are viewing is simply the auto-wordwrap of your program. See for example https://ideone.com/WHDgw6 – xanatos Jan 01 '21 at 12:52
  • @xanatos that's right. I used \t to have spaces between them. will you take a look at the picture I uploaded and help me to get the column under 100 also filled? – estrella Jan 01 '21 at 13:15
  • Consoles are resizable. There is no fixed size for them. I've just noticed that there is something funny: the initial size of the console is used as the "maximum size"... If you shrink it, the text will be re-wordwrapped, but the text won't ever go over the maximum size, even if you enlarge it. – xanatos Jan 01 '21 at 13:19
  • @xanatos Which is quite terrible and one of the main reasons I tend to rerun/recompile stuff :) – Camilo Terevinto Jan 01 '21 at 13:27

1 Answers1

1

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();
xanatos
  • 109,618
  • 12
  • 197
  • 280