+ 2

Plz explain me this code

What is exactly happening here 👇 #include <iostream> using namespace std; int main() { int x=3; while (x++<10){ x+=2; } cout<<x; return 0; }

9th Oct 2021, 3:56 PM
Jainil Raval
Jainil Raval - avatar
8 Respuestas
+ 2
Krishnendu Dey Let's examine x is initialized to 3, then we enter the while loop Pass 1 x is less than 10 so ++ x is now 4 then +=2 and x is now 6 Pass 2 x is less than 10 so ++ x is now 7 then +=2 and x is now 9 Pass 3 x is less than 10 so ++ x is now 10 then +=2 and x is now 12 Pass 4 x is not less than 10 so ++ x is now 13 We fall out of the while loop We cout<<x and 13 is displayed in the console
9th Oct 2021, 4:39 PM
Paul K Sadler
Paul K Sadler - avatar
+ 4
Yes Paul K Sadler sir, you are right , the correct output is 13, I just missed the last post increment to calculate. But I think you just misunderstood something, I neither upvoted nor downvoted any answer/question of this post. You can clarify by referring to any moderator. Regards!!!
9th Oct 2021, 5:02 PM
Saurabh
Saurabh - avatar
+ 3
As long a the value of x is smaller than 10 the loop continues and x is increased by 2. At the beginning of each iteration x is evaluated if it is still smaller than 10, then it is increased by 1
9th Oct 2021, 4:14 PM
Lisa
Lisa - avatar
+ 2
It will print 12, cause loop will execute 3 times and each time in loop the value of x is increased by 3. the correct output will be 13, thanks for correcting me Paul K Sadler .
9th Oct 2021, 4:41 PM
Saurabh
Saurabh - avatar
+ 2
Saurabh Kumar Yadav Actually that is not correct. The condition is evaluated as false and then the ++ increments x to 13 before falling out of the while loop.
9th Oct 2021, 4:43 PM
Paul K Sadler
Paul K Sadler - avatar
+ 2
Paul K Sadler Thank you sir for explaining 🙏
10th Oct 2021, 1:15 PM
Jainil Raval
Jainil Raval - avatar
+ 2
Lisa Thank you for explaining 🙏
10th Oct 2021, 1:17 PM
Jainil Raval
Jainil Raval - avatar
+ 1
Saurabh Kumar Yadav my apologies on the comment about the downvote. My post was downvoted at the time I made the comment. I assumed that was you since no others had posted. And after I suggested it be removed in my post to you it was removed (assuming you responded to my comment, I edited out my comment about the downvote). It must have been someone else. Again, my apologies for assuming it was you. I see now it wasn't as I have no reason to doubt your honesty. Up or downvotes are not a big deal to me. I just mention it to encourage users to opine in a constructive comment so that we all can learn. Thanks for speaking up and continuing the conversation.
9th Oct 2021, 5:11 PM
Paul K Sadler
Paul K Sadler - avatar