Isn't this answer wrong? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Isn't this answer wrong?

int x=0; while (x <5) { x = x++; } this will cause an infinite loop. but the quiz answer mentions this as finite loop. How to get this corrected?

31st Jan 2017, 6:25 AM
Chetan Dugar
Chetan Dugar - avatar
12 Answers
+ 16
It is an infinite loop. The answer to the question is wrong
31st Jan 2017, 7:09 AM
Filip
Filip - avatar
+ 8
Ok follow Filip's answer xd
31st Jan 2017, 7:16 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 7
Every time I encounter this question, my conscience kills me.
31st Jan 2017, 8:27 AM
Hatsy Rei
Hatsy Rei - avatar
+ 7
x = x++ is similar to: var tmp = x; x++; x = tmp; So yeah, infinite loop... Source: http://stackoverflow.com/a/226019
31st Jan 2017, 9:49 AM
Jafca
Jafca - avatar
+ 7
yes this is an infinite loop only but if u encounter this question in Java then the quiz answer would also be infinite loop only....I lost a match due to this , I thought in Java also they would have done wrong so I gave that it's not infinite and came to know that here the answer is the correct one only
31st Jan 2017, 4:08 PM
Sakshi👸
Sakshi👸 - avatar
+ 6
Yeah I'm probably wrong because I don't know C++...
31st Jan 2017, 6:54 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 4
just run this code and see. x = x++ changes nothing about x
31st Jan 2017, 6:53 AM
Chetan Dugar
Chetan Dugar - avatar
+ 4
@steven Look at all the answers first, including mine. You might find your answer xD
31st Jan 2017, 11:21 AM
Jafca
Jafca - avatar
+ 1
No, it is finite. First loop, x = 1 ...... Fifth loop, x = 5 The while loop stops. (This thing is wrong)
31st Jan 2017, 6:51 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 1
Why is it infinite? x = x++ uses the value of x and then increments it meaning that x now = 1 ... if this is in fact infinite, then i also need some clarification. seems like a valid loop to me??
31st Jan 2017, 11:19 AM
steven
steven - avatar
+ 1
@Jafca I have read the other posts but my logic keeps telling me this looks right. why is x++ not incrementing x? and if it is, then shouldnt this be finite? EDIT never mind, it just clicked... i can see it now.
31st Jan 2017, 11:27 AM
steven
steven - avatar
+ 1
It is infinite . because x++ is post increment ! x=x++ is not a useful function as it is equal to x=x (post increment meaning ) and everytime the loop exits , x value is retained before it goes into the loop again i.e it doesn't get incremented outside the loop !
31st Jan 2017, 3:59 PM
Nitish ML
Nitish ML - avatar