user2895432
user2895432

Reputation:

C# Nested for loops creating unexpected results depending on braces

I seem to be having a problem when creating nested for loops with C#. When the nested Loop has braces, the result isn't as expected, whereas with braces the result is as expected.

The code:

int i, j, k;

for(i=1; i<=5;i++) // this loops 5 times. 
{
   for (j = 5; j > i; j--)
   {
      Console.Write(" ");
      Console.WriteLine("0");
   }
}

Expected:

    0
   0
  0
 0
0

Result:

  0
  0
  0
  0
  0
  0
  0
  0
  0
  0
  0

I don't understand why, if I negate the nested braces, I will get the expected answer, but I am unsure why with them it doesn't work.

Upvotes: 0

Views: 147

Answers (4)

Esteban Elverdin
Esteban Elverdin

Reputation: 3582

You put the braces in the wrong place, try this:

 int i, j, k;

 for(i=1; i<=5;i++) // this loops 5 times. 
 {
    for (j = 5; j > i; j--)
    {
        Console.Write(" ");
    }

    Console.WriteLine("0");
 }

If you don't put braces, it works because only the sentence below the for statement is in the loop

 for(i=1; i<=5;i++) // loop A
 {
    for (j = 5; j > i; j--)  // loop B
        Console.Write(" ");  // in scope of loop B
    Console.WriteLine("0");  // in scope of loop A
 }

Upvotes: 3

Anarion
Anarion

Reputation: 2534

this can be done in a shorter way:

for(int i = 5; i > 0; --i)
    Console.WriteLine(new String(' ', i) + 0);

Upvotes: 0

user1854438
user1854438

Reputation: 1842

Because Console.WriteLine("0"); will give a return.

Try this

   for(i=1; i<=5;i++) // this loops 5 times. 
    {
        for (j = 5; j > i; j--)
        {
            Console.Write(" ");
        }
        Console.WriteLine("0");
    }

Upvotes: 0

johnny
johnny

Reputation: 2122

take this Console.WriteLine("0");out of the first loop.

Upvotes: 0

Related Questions