why am I getting the following output: 4 8 12 16 20
int i, j = 1, k;
for (i = 0; i < 5; i++)
{
k = j++ + ++j;
Console.Write(k + " ");
}
why am I getting the following output: 4 8 12 16 20
int i, j = 1, k;
for (i = 0; i < 5; i++)
{
k = j++ + ++j;
Console.Write(k + " ");
}
Well k = j++ (+) ++j
j++ will increment the value of j, but return the pre-incremented value.
++j will increment the value of j, and then return the incremented value.
j++ = 2 but really returns (1)
although, as soon as you hit ++j, you are incrimenting the real value of j which currently is 2.
++j = 3
1 + 3 = 4
I don't think the other answers here are correct.
The variables are evaluated in order according to mathematical ordering operations. In this case, we are just adding, so they are evaluated left to right. j++
and then ++j
j++ + ++j
j
let's call the value of j
at the start of the loop p
j++
j
evaluates to the pre-increment value (p
) and then j
is incremented (p+1
)++j
j
is incremented (p+2
) and evaluates as the post-increment value (p+2
)So, the two evaluated numbers are p
+ p+2
:
i initial j j++ + ++j k j
================================
0 1 1 + 3 4 3
1 3 3 + 5 8 5
2 5 5 + 7 12 7
3 7 7 + 9 16 9
4 9 9 + 11 20 11
j++
increments the value of j, but returns the pre-incremented value.++j
increments the value of j, but returns the incremented value.In C#, the + operator is just a function, and in your case, j++
and ++j
are the arguments to the function. Evaluation of function arguments proceeds from left to right, so here's what we get for each iteration of the loop:
j++
increments the value of j
, but returns the original value.++j
increments the value of j
again and returns the new value.+
operator is called with the results from (1) and (2).For example, when i==0
, j
is initially 1
. Then j++
executes, setting j
to 2
, and returns 1
. Then ++j
increments j
to 3
, and returns 3
. So the addition becomes 1 + 3
, resulting in k = 4
.