Reputation: 267
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?
Upvotes: 2
Views: 921
Reputation: 73
If alter 1 with i in second loop then it will work same
for (int j = **i**; j <= i; j++)
Console.Write('+');
Console.WriteLine();
Upvotes: 0
Reputation: 98810
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?
Upvotes: 5
Reputation: 22690
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
Upvotes: 4
Reputation: 13628
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.
Upvotes: 2