-5

Why does While loop post-increments (or post-decrements) a variable right after examination of the condition and not after the whole loop?

As in:

int x = 0;
while (x++ < 5)
Console.WriteLine(x);

The output is: 1 2 3 4 5, when I believe it should be 0 1 2 3 4. It seems it checks the condition - true - inrements right away. Is that normal behaviour, becase I've recently been practising Plain C and it's completely different.

Should I rather go with this option for more clarity?

while (x < 5)
Console.WriteLine(x);
++x; 
Matt
  • 31
  • 1
  • 4

5 Answers5

8

If you would use a for loop your expected answer would be correct: the while does not have any special inner workings like that.

for (x = 0; x < 5; x++)

is the way to write this with the most clarity.

ikdekker
  • 425
  • 3
  • 11
2

The behavior is correct and ANSI-C does it in the same way, if you execute the same code.
x++ is "one command" and the increment is already done as soon as you move on to the next command. The difference between x++ and ++x is, that the later one returns the "new value" and the first one returns the "old value".
May the following be what you want:

int x = 0;
do
{
    Console.WriteLine(x++);
}
while (x < 5);

But I also think in general this specific case of "do it 5-times" is best solved with a for-loop as suggested by @ikdekker.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
2

Your loop is equivalent to:

int x = 0;
while (x < 5)
{
  x++;
  Console.WriteLine(x);
}

Since the incrementation will be done immeditely after the condition line (x<5).

So your second loop is the correct one (you should add braces though), or if you really want condition and increment in the same time you can use the do..while loop:

int x = 0;
do
{
  Console.WriteLine(x);
} while (++x < 5);
Oxald
  • 837
  • 4
  • 10
0

You can use a for loop for this as has been mentioned. You can also declare the x variable inside the for loop.

for (var x = 0; x < 5; x++)
{
    Console.WriteLine(x);
}
0

you are using x++ in the wrong place

Console.WriteLine(x++)

instead of

while(x++ < 5)

mark as answer if it helps