What is the happening in this case? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the happening in this case?

int x=3; while(x++<10) { x+=2; } cout<< x; After completing the 2nd loop the value of 'x' becomes 9, and when it checks for the condition for the 3rd loop i.e. 9++<10 meaning 10<10 Shouldn't that be false? But that's considered to be true by compiler. Even if I put the condition like while(x++<=10) It is showing the same output

2nd Apr 2020, 5:42 PM
Purvank Bhiwgade
Purvank Bhiwgade - avatar
2 Answers
+ 17
Purvank Bhiwgade Initially the value of x is 3. When the loop executes - while (x++ < 10) First it checks (3 < 10), the condition is true. Since here ++ is post increment operator (x++) that's why it performs operations in following way - 1 - checks condition 2 - Increment value 3 - Then enters in loop So after this (x++ < 10) means- (3 < 10) condition is true and value of x is incremented by 1 so it becomes 4 , then it enters in loop x += 2; value of x = (4 + 2)becomes 6. Agai it checks the condition while(x++ < 10) , here value of x is 6. The condition is true (6 < 10) And then value is incremented by 1, So x becomes 7, then It enters in loop and execute x += 2; And value of x = (7 + 2)becomes 9. Again it checks condition (9 < 10), the condition is true , then the value of x becomes 10 and again it enters in loop x = (10+2) at last value of x becomes 12.
2nd Apr 2020, 6:05 PM
Vinesh Wadhwani
Vinesh Wadhwani - avatar
+ 1
X++ is post increment, meaning it will evaluate the value, then increment it , then it will finally store it.
2nd Apr 2020, 6:44 PM
Jay W