-4

I'm trying to remove {} in a nested for but for some reason it doesn't seem to work.

public void PrintBoard()
{
    for (int i = 0; i < _matrix.N; i++)
    {
        for (int j = 0; j < _matrix.M; j++)
        {
            Console.Write(_matrix.Get[i, j]);
        }
        Console.WriteLine();
    }
}

This is what I'm trying, but the output is kinda different, it seems that the line breaks doesn't work properly. I also would like to know why it's behaving like that.

public void PrintBoard()
{
    for (int i = 0; i < _matrix.N; i++)
       for (int j = 0; j < _matrix.M; j++)
           Console.Write(_matrix.Get[i, j]);
       Console.WriteLine();
}

// Output
// .........

// Output expected
// ...
// ...
// ...
Sharki
  • 404
  • 4
  • 23
  • 5
    Indent means nothing to the C# compiler. It's a best practice to leave these brackets in precisely for the reason you've run into... it's not always clear what goes with what when there are no braces. You are expecting that the second `Console.WriteLine()` is inside the second `for` loop but it's not. – JeffC Nov 18 '21 at 19:44
  • @JeffC I was expecting `Console.WriteLine()` in the first `for` tho... But yeah it seems like the second `for` counts as the first statement for the first `for` and the `Console.WriteLine()` as a second one, right? – Sharki Nov 18 '21 at 19:50
  • 1
    No, only the second `for` is inside the first `for` - the `Console.WriteLine` is outside of the `for` loop since the `for` only includes the next statement if there are no brackets. – D Stanley Nov 18 '21 at 19:51
  • 2
    @DStanley Sorry I meant that, that because the second for is the first statement, and there are no brackets `Console.WriteLine` count as a second statement and because of that it does't work (bc it only works the first statement by its nature). My bad, I explained it badly, thanks! – Sharki Nov 18 '21 at 19:53

1 Answers1

2

This is because you can only remove the braces of the inner foreach, since the outer forceach has 2 statements in the block.

public void PrintBoard()
{
    for (int i = 0; i < _matrix.N; i++)
    {
        for (int j = 0; j < _matrix.M; j++)
            Console.Write(_matrix.Get[i, j]);
        Console.WriteLine();
    }
}
sommmen
  • 6,570
  • 2
  • 30
  • 51