In this chapter, we will learn about the break and continue statement along with their implementation.
break Statement
The break statement terminates the loop and the program flow moves to the next line of code outside of the loop.
The syntax of the break statement is:
break;
break with for Loop
void main() {
for (int num = 1; num <= 5; num++) {
if(num == 3) {
break;
}
print(num);
}
}
Output
1
2
In the above example, we have used the break statement inside the for loop.
Inside the for loop, in each iteration, we are printing the num variable.
When the num variable increments to 3, the program encounters the break statement.
if(num == 3) {
break;
}
And the loop terminates.
As you can see in the output, only 1, 2, and 3 are printed as an output.
break with while Loop
void main()
{
var num = 0;
while(num < 5){
num = num + 1;
if(num == 3){
break;
}
print(num);
}
}
Output
1
2
In the above example, we have used the break statement inside the while loop. The while loop prints the number from 1 to 5.
The break statement is used with the condition that if the number is 3, the loop terminates.
if(num == 3){
break;
}
When the num variable increments to 3, the program encounters the break statement. And the loop terminates
continue Statement
The continue statement skips over the current iteration and moves to the next iteration.
The syntax of continue statement is:
continue;
continue with for Loop
void main() {
for (int num = 1; num <= 5; num++) {
if(num == 3) {
3 is skipped
continue;
}
print(num);
}
}
Output
1
2
4
5
Here, the above program skips over the current iteration when it encounters the continue statement.
Hence, when the num variable is 3, it skips the print statement. And the output only displays 1, 2, 4 and 5.
continue with while Loop
void main()
{
var num = 0;
while(num < 5){
num = num + 1;
if(num == 3){
print("3 is skipped");
continue;
}
print(num);
}
}
Output
1
2
3 is skipped
4
5
In the above example, we have used the continue statement inside the while loop.
The while loop in the above example prints the number from 1 to 5. When the value of num variable reaches 3, the program encounters the continue statement. And the current iteration is skipped.
Hence, 3 is not printed on the output.
Note: break and continue statements are used with if…else and switch statements.