NoviceCoder11
NoviceCoder11

Reputation: 33

C#: Why is the final value for x different to the value outside the for loop?

static void Main(string[] args)
{
    double x;
    for (x = 0; x < 5; x++)
    {
        Console.WriteLine(x);
    }
    Console.WriteLine(x);
}

My code prints out this as a result of the for loop: 0 1 2 3 4

and the

Console.WriteLine(x);

which is outside the loop prints the value 5. Why is it incrementing x by 1 outside the loop?

Upvotes: 3

Views: 142

Answers (4)

Idos
Idos

Reputation: 15320

It is because the for is still being executed on the 5th time.
But it doesn't enter it since x<5 is being evaluated to false.
That is why in most cases a variable that has been defined inside a for loop isn't going to be used after it.

Upvotes: 5

Sergii Zhevzhyk
Sergii Zhevzhyk

Reputation: 4202

In the last cycle x equals to 5 because it was icremented but didn't pass the check x<5. That's why it prints 5 in the end.

I found a similar example on MSDN. I adapted the explanation to your example.

  1. First, the initial value of variable i is established. This step happens only once, regardless of how many times the loop repeats. You can think of this initialization as happening outside the looping process.
  2. To evaluate the condition i < 5, the value of i is compared to 5.

    • If i is less than 5, the condition evaluates to true, and the following actions occur: The Console.WriteLine statement in the body of the loop displays the value of i. The value of i is incremented by 1. The loop returns to the start of step 2 to evaluate the condition again.

    • If i is greater than or equal to 5, the condition evaluates to false, and you exit the loop.

Upvotes: 2

ujwal dhakal
ujwal dhakal

Reputation: 2469

The value was already increased to 5 the memory hold at last. And no any further check was made outside the loop

Upvotes: 0

Daniel Cook
Daniel Cook

Reputation: 244

The loop increments x each iteration, and breaks out only when it is not < 5. Hence to break out of the loop it must logically be 5.

Upvotes: 1

Related Questions