The ‘break’ statement is used to take the control out of the loop even before it’s maturity. It is used within the loop body and duly packed inside of an ‘if’ statement. When the condition written with ‘if’ statement goes TRUE, the break statement executes and the loop terminates right there.
Syntax:
Example:
This code will print:
Here, you can see that the value of ‘i’ started from 5 and went up to -5 thus making exact 11 iterations but the result is just 5 values. This is because, while decrementing, when ‘i’ became zero, the break statement executed thereby ending the loop prematurely.
The ‘continue’ statement is used to take the control to the next iteration of the loop leaving the rest of the loop body un-executed. It is used within the loop body and duly packed inside of an ‘if’ statement. When the condition written with ‘if’ statement goes TRUE, the ‘continue’ statement executes and the loop take a jump of one iteration right there.
Syntax:
Example:
This code will print:
Here, you can see that the value of ‘i’ started from 5 and went up to -5 thus making exact 11 iterations but the result is just 10 values. This is because, while decrementing, when ‘i’ became zero, the continue statement executed thereby skipping the loop to the next iteration.