cybernautmik
cybernautmik

Reputation: 63

Why is the output giving me a value of +1?

The code

public static void InitializeArray(ref double[] doubleA)
{
    //array init using foreach
    int i = 0;
    foreach (double dub in doubleA)
    {
        doubleA[i++] = i + .5;
    }
}

is giving me an output of

doubleA[0] = 1.5 instead of .5

doubleA[1] = 2.5 instead of 1.5

and so on

I'm not understanding why it's doing that. As I understand it, doubleA[0] should be getting 0.5 because I'm only adding 0.5 so where is the extra 1 coming from? I'm thinking it's from int i but for i=0, shouldn't it evaluate to doubleA[0] = 0 + .5?

So far I have tried writing doubleA[i++] = i + .5; instead which gives each element in the array just the value of 0.5.

Upvotes: 0

Views: 77

Answers (2)

spender
spender

Reputation: 120380

So let's start with i = 0

doubleA[i++] = i + .5;

Here you are accessing position 0 of the array, but also adding 1 to the value of i. When i == 0, the expression i++ will be the value 0, but the value of the variable i is incremented such that the new value of i is 1.

On the right hand side, this new value of i is used (1) and added to 0.5. Giving a value of 1.5 which is assigned back to index 0 of the array (as indicated on the left hand side of the assignment).

I could go on, but I think you probably get it by now...

Further reading on operator ++

Upvotes: 3

Blue
Blue

Reputation: 22911

This is because i is being incremented in your key: doubleA[i++]. i++ will increment the key by one, AFTER returning it. When it's used later (as the value), its value has already been incremented. So now you're setting it to 1 + 0.5.

Let's break this down, and show you the functional equivalent, and you'll see exactly what this is happening:

public static void InitializeArray(ref double[] doubleA)
{
    //array init using foreach
    int i = 0;
    foreach (double dub in doubleA)
    {
        int key = i;
        i = i + 1;
        doubleA[key] = i + .5;
    }
}

Upvotes: 1

Related Questions