Search code examples
c#for-loopdifferencebrackets

Difference between using brackets in for loop C# and not using it


The output of the following code is different from the ouput from the second code can someone explain the problem?

Code 1:

for(int i = 1; i <= intInput; i++)
{
    for(int j = 1; j<=i; j++)
    {
        Console.Write('+');
        Console.WriteLine();
    }                         
}
if intInput is 4 Ouput is:
+
+
+ 
+

Code 2:

for(int i = 1; i <= intInput; i++)
{
    for(int j = 1; j<=i; j++)
        Console.Write('+');
        Console.WriteLine();                                    
}
if intInput is 4 Ouput is:

+
++
+++
++++

I know how this line of codes works but i dont understand what difference the brackets make on both codes?


Solution

  • When you write;

    for(int j = 1; j <= i; j++)
    {
        Console.Write('+');
        Console.WriteLine();
    }
    

    Both Console line works until j loops out.

    But when you write

    for(int j = 1; j <= i; j++)
        Console.Write('+');
        Console.WriteLine();    
    

    Only first Console works until j loops out. That's why second one is equal to;

    for(int j = 1; j<=i; j++)
    {
       Console.Write('+');
    }
    Console.WriteLine();    
    

    If there is one statement included in the loop, the curly brackes can be omitted. But using them is always a better approach.

    Read: Why is it considered a bad practice to omit curly braces?