+ 1

Can some one explain this code to me please. I'm lost on why the answer is 13.

int x =3; while(x++<10){ x+=2; } cout << x;

8th Oct 2019, 9:36 AM
Marcus Landry
Marcus Landry - avatar
5 Respostas
+ 2
Remember x = 3 in while loop x in post incrementing which means x won't update after using in next statement. So 1st time x=3which is less than 10 Then x become 3+2 equals to 5 then 5 which is x increment by 1 equals 6 2nd time x is 6 less than 10 true Then x become 6+2 equals to 8 then 8 which is x increment by 1 equals 9 3rd time x is 9 less than 10 true Then x become 9+2 equals 11 then 11 which is x increment by 1 equals 12 4th time x is 12 which is false but X is post incrementing inside while loop so it print 13 after incrementing x by 1.
8th Oct 2019, 9:45 AM
Chirag Kumar
Chirag Kumar - avatar
+ 1
Marcus Landry our x is at 12 when compiler check condition inside while which is x++<10 or 12 < 10 which is false so it won't go inside while loop. In short : due to less than operator (<).
8th Oct 2019, 12:45 PM
Chirag Kumar
Chirag Kumar - avatar
0
Thanks so much! I totally missed the loop it makes sense though bc the code will continue to run until after.
8th Oct 2019, 9:48 AM
Marcus Landry
Marcus Landry - avatar
0
Yes right !!
8th Oct 2019, 9:58 AM
Chirag Kumar
Chirag Kumar - avatar
0
So just to be sure the last one displayed will always be false? Iss the due to the while, ++ or the <?
8th Oct 2019, 12:19 PM
Marcus Landry
Marcus Landry - avatar