[Solved] How is the code interpreted if no curly braces follow a while loop?


A while loop without braces is the same as a while loop with braces surrounding the line immediately below it:

int num = 0;
while(++num < 6) 
{
    Console.WriteLine(++num);
}
Console.WriteLine(num++);
Console.WriteLine(++num);

First iteration:

while(1 < 6) // num is 1
{
    Console.WriteLine(2); // num is 2
}

Second iteration:

while(3 < 6) // num is 3
{
    Console.WriteLine(4); // num is 4
}

Third iteration:

while(5 < 6) // num is 5
{
    Console.WriteLine(6); // num is 6
}

On the fourth iteration, num becomes 7 and then gets checked by < 6, which evaluates to false. The while loop exits and the two lines below gets executed.

// num is 7
Console.WriteLine(7); // num is 8
Console.WriteLine(9); // num is 9

So it prints 2, 4, 6, 7, 9

1

solved How is the code interpreted if no curly braces follow a while loop?