Loop control statements: There may be some situations when you have to come out of loop immediately without reaching at end or there may also be some situations that you need to skip one or two iterations within loop and move to the next iteration.
break statement: The break statement is used to break the loop immediately on the bases of any condition
Entering the loop 1 2 3 4 Exiting the loop
- Initialize x = 1.
- while(x<20), loop will move until x is less than 20.
- Print each value of x , x will increment by 1 each time.
- if(x==5), when x will equals to 5 then loop will break and control will exit out from loop.
break statement can also use with switch-case statement.
continue statement: When the continue statement occurs in loop , it skip the whole remaining code and check the entering condition again. If the condition is still true then loop run for next iteration otherwise the control comes out of loop.
Entering the loop 1 2 3 4 6 7 8 9 10 Exiting the loop Value 5 is skipped!!!
- Initialize x=0.
- Loop will move till x is equal to 10.
- In each iteration x is incremented by 1.
- When x is equals to 5 , loop will exit with running print statement.