Increment operator used in a while loop's condition | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Increment operator used in a while loop's condition

#include <iostream> using namespace std; int main() { int x = 3; while (x++ < 10) { x+=2; } cout<<x; return 0; } // outputs 13 How did we get to 13? My thought process: run 1 gives 6 (Because x++ in the condition turns x=3 into x=4. Statement x+=2 thus gives 6) run 2 gives 9 (Because x++ in the condition turns x=6 into x=7. Statement x+=2 thus gives 9) run 3 is a no go because x++ in the condition turns x=9 into x=10, making the condition false and stoping the while loop...

23rd Jul 2020, 10:20 AM
Solus
Solus - avatar
4 Answers
0
in while loop, x++ is a post increment, which means when the condition is checked , after that the value of x will change.. so after while(3< 10) x becomes 4 and x+=2 will give x= 6 , and after while(6 < 10) x becomes 7 and x+=2 will give x= 9, and after while(9< 10) x becomes 10 and x+=2 will give x= 12 and next cond fails for x<12 but x++ will happen making it 13
23rd Jul 2020, 10:25 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
0
x++ post incrementing values each time that means in the third scenario the comparison was among 9 < 10 where 10 obviously is greater. so, the code runs again two times
23rd Jul 2020, 10:31 AM
zexu knub
zexu knub - avatar
0
For post increment, the incrementation happens even though the condition is false. Thank you @codemonkey.
23rd Jul 2020, 10:33 AM
Solus
Solus - avatar
0
Solus The condition wasn't false when while loop compared it. x is incremented afterward that means it was 9 otherwise while loop didn't run and the output would be 10
23rd Jul 2020, 10:46 AM
zexu knub
zexu knub - avatar