2

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
moji
  • 267
  • 5
  • 15
  • 1
    If you don't specify curly braces it will consider first statement immediate to the for statement as inside the for loop to be repeatable. – Jenish Rabadiya Nov 06 '15 at 10:31
  • 2
    looks like some kind of homework. Why you don't use the debugger to find out yourself? – Dom84 Nov 06 '15 at 10:34
  • Or you are a Python programmer. :) In Visual Studio, I always always use ctrl+k, ctrl+d to format the document, and then you also see nested if/for/class/whatever code a lot better. – Andreas Reiff Nov 06 '15 at 10:53

4 Answers4

5

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?

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
4

You second case effectively means:

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

Indentation means nothing for compiler it is only for you

ISanych
  • 21,590
  • 4
  • 32
  • 52
2

The loop has a scope. If you do not include the braces, only the first line is in the loop. If you have the braces, everything inside falls under the scope of the loop.

In this case, the first example write a "+" to the console as well as a new line every iteration of the inner loop.

The second case, the inner loop only executes the "+" writing on each inner iteration. The outer loop adds the new line.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
0

If alter 1 with i in second loop then it will work same

for (int j = **i**; j <= i; j++)
   Console.Write('+');
   Console.WriteLine();
Fuad Teymurov
  • 73
  • 1
  • 10