Why does while() sometimes go one step above? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why does while() sometimes go one step above?

I keep coming across tasks where while goes above the value it is supposed to. For an example: int i = 9, x = 2; while(i-->3) { ++x; if(x<=4) continue; else if(x<=6) x+=3; else break; } In this case while will break after 4 loops, x will first be 3, then 4, then 5 and then 6+3=9. Why does it get to 5 when it's set to stop continuing after 4? Can someone please explain this?

9th Mar 2020, 12:44 PM
Prof
Prof - avatar
2 Answers
+ 4
Continue does not mean stop continuing. It means that everything after continue will not be executed and the control returns to the beginning of the loop.
9th Mar 2020, 1:46 PM
Avinesh
Avinesh - avatar
+ 2
continue statement causes to skip instructions next to that and proceeds with next iteration. In that code, if condition fails when 5<=4, and else if part get executed, in next iteration breaks the loop.. Continue means only skip correct iteration right now, and continue with next iteration..
9th Mar 2020, 1:46 PM
Jayakrishna 🇮🇳