C# Programming - Operators - Discussion

Discussion Forum : Operators - General Questions (Q.No. 16)
16.
What will be the output of the C#.NET code snippet given below?
int i, j = 1, k;
for (i = 0; i < 5; i++)
{
    k = j++ + ++j;
    Console.Write(k + " ");
}
8 4 16 12 20
4 8 12 16 20
4 8 16 32 64
2 4 6 8 10
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
11 comments Page 1 of 2.

Megha S said:   1 decade ago
i = 0, j = 1

k = 1 + 3 = 4

i = 1, j = 3

k = 3 + 5 = 8

i = 2, j = 5

k = 5 + 7 = 12

i = 3, j = 7

k = 7 + 9 = 16

i = 4, j = 9

k = 9 + 11 = 20

Meenalosani said:   1 decade ago
Thank you megha :-)

Munish said:   1 decade ago
Nice logic megha!

Rishabh said:   1 decade ago
Realy nice logic megha.

Rupesh said:   1 decade ago
i = 0, j = 1

k = 2 + 2 = 4 /*k = j++ + ++j;
k = j++ + ++1
k = j++ + 2
k = 2 + 2 and j=3 b/c of j++
k = 4 and j=3 */

i = 1, j = 3

k = 4 + 4 = 8

i = 2, j = 5

k = 6 + 6 = 12

i = 3, j = 7

k = 8 + 8 = 16

i = 4, j = 9

k = 10 + 10 = 20
(1)

Nguyennamhsm said:   1 decade ago
i = 0, j = 1.

k = 1 + 3 = 4 //first j =1 | after j++ -> j increment by one =2 when ++k this time k has really value is 2 ->k++ + ++k = 1+(k+1) = 3.

i = 1, j = 3.

k = 3 + 5 = 8.

i = 2, j = 5.

k = 5 + 7 = 12.

i = 3, j = 7.

k = 7 + 9 = 16.

i = 4, j = 9.

k = 9 + 11 = 20.

Niths said:   1 decade ago
j=1 & i=0
j++ = 1+1=2
++j= 2 (this is result after increment by 1 it will ++j=1+2=3 so j=3)
K=2+2=4.

j=3 & i=1
j++ = 3+1=4
++j= 4 (this is result after increment by 1 it will ++j=1+4=5 so j=5)
K=4+4=8.

j=5 & i=2
j++ = 5+1=6
++j= 6 (this is result after increment by 1 it will ++j=1+6=7 so j=7)
K=6+6=12.

j=7 & i=3
j++ = 7+1=8
++j= 8(this is result after increment by 1 it will ++j=1+8=9 so j=9)
K=8+8=16.

j=9 & i=4
j++ = 9+1=10
++j= 10 (this is result after increment by 1 it will ++j=1+10=11 so j=11)
K=10+10=20.

Ahmed said:   9 years ago
Can anyone tell me the difference between ++ prefix and post?

Jitendra Nayak said:   9 years ago
Thank you very much @Megha S.

Virendra said:   8 years ago
Nice logic @Niths.


Post your comments here:

Your comments will be displayed after verification.