I know it might be too easy for some of you but I came across this simple code and I don't know why the answer is that. Would you please explain where I am mistaken line by line.
1 2 3 4 5
int x=3;
while (x++<10) { // 1) x=3,(after it comes down to x++), then x=5
x+=2; // 2) x=6 (after x++), then x=8
} // 3) x=9 (after x++). then x=11
cout <<x;
The right answer is 13 and I can't figure out why. Your help is much appreciated. Thanks in advance.
this is just interview/test type question that is intentionally hard to follow.
x is 3.
is x<10? x is incremented to 4.
it was < 10.
add 2, x is 6.
is x < 10? add 1
x is 7.
add 2, x is 9.
is x < 10, add 1
x is 10.
add 2, x is 12
is x < 10? it isnt, add one. //the ++ happens whether the condition is true or false!!! this is likely what you missed.
x is 13.
Thanks, that's clear now! It was really tricky and I didn't know that the last time we increment it ++(when the condition is wrong), it adds 1 even then and makes it 13.