What is the Difference Between Break and Continue Statement?
In programming, there are two commonly used loop control statements named `break` and `continue`. They are both used to alter the flow of control inside loops, however, they serve different purposes. In this article, we will explore the difference between break and continue statement in programming.
Break Statement
`break` statement is used to prematurely terminate the loop execution. When the `break` statement is encountered inside a loop, the control jumps outside the loop and continues with the next statement immediately after the loop.
The following is an example of the break statement used in a for loop:
“`
for(int i=0; i<10; i++){
if(i == 5){
break;
}
System.out.println(i);
}
```
In this example, the `break` statement is executed when `i` is equal to 5, which means the loop execution stops immediately, and the loop is terminated. Consequently, the output of the loop will only print the values of `i` from 0 to 4.
Continue Statement
The `continue` statement is another loop control statement that is used to skip an iteration in a loop. When the `continue` statement is executed inside a loop, control immediately jumps back to the beginning of the loop for the next iteration.
Here’s an example of the continue statement in a for loop:
“`
for(int i=0; i<10; i++){
if(i == 5){
continue;
}
System.out.println(i);
}
```
In this example, the `continue` statement is executed when `i` is equal to 5, which causes the loop to skip to the next iteration. Consequently, the output of the loop will print the values of `i` from 0 to 9, except for the value of 5.
Conclusion
In conclusion, `break` and `continue` statements are both used to alter the flow of control inside loops, but they serve different purposes. Whereas the `break` statement is used to terminate the loop, the `continue` statement is used to skip an iteration in the loop. Understanding the difference between these two statements is fundamental to writing efficient and effective loops in programming.
Table difference between break and continue statement
Break Statement | Continue Statement |
---|---|
Terminates the execution of a loop entirely | Skips the current iteration of a loop and continues to the next |
Can only be used inside a loop | Can be used inside loops, switch statements, and labeled statement blocks |
Cannot be used in if statements or functions | Can be used in if statements and functions |
Used to prematurely end a loop when a certain condition is met | Used to skip over certain values in a loop and continue on to the next iteration |