Break and Continue Statement

0 woodrowkosovich December 8, 2020

Break Statement:

The break statement terminates the execution of the loop and the control transfers to the statement immediately following the loop. Generally, the loop terminates when its test condition is false. But if we have to terminate the loop instantly without testing loop termination condition, the breakstatement is useful. The syntax for this is:

break;
Break Statement with for loop
Break Statement with for loop

We also use break statements in the switch statement which causes a transfer of control out of the entire switch statement, to the first statement following the switch statement. The switch statement will discuss in the next chapter.

Let’s loop at one example to make a clear concept on the break statement.

<?php

for($i = 1; $i <= 10; $i++){
    echo "The value of x = $i";
    if(x == 5){
        break;
    }
}

?>

The output of the above program is:

The value of x = 1
The value of x = 2
The value of x = 3
The value of x = 4
The value of x = 5

In this example, the counter variable x is initialized to 1 and the test condition $i <= 10. Thus, the loop body executes 10 times (i.e. 1 to 10). But the use of the break statement within the body of the loop has terminated the loop when the value of x becomes 5. Thus its output is only the numbers from 1 to 5 instead of 1 to 10;

Continue Statement:

The continue statement to use to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Instead, the remaining loop statements are skip and the computation proceeds directly to the next pass through the loop. 

The syntax of for this statement is:

continue;
Continue statement with for loop
Continue statement with for loop

Lets loop one example to make clear concepts on continuestatement:

#include  <stdio.h>

int main(){

    int x;

    for ( x=1; x <= 10; x++ )
    {
        if( x == 5)
        {
            continue;
        }
        printf("The value of x = %d", x);
    }

    return 0;
}<?php

for($i = 1; $i <= 10; $i++){
    if(x == 5){
        continue;
    }
    echo "The value of x = $i";
}

?>

The output of the above program is:

The value of x = 1
The value of x = 2
The value of x = 3
The value of x = 4
The value of x = 6
The value of x = 7
The value of x = 8
The value of x = 9
The value of x = 10

In this example, When the value of x is 5 the continue statement executes so that the print statement is not executed. The continue statement to bypass the print statement following the continue statement and the loop executes for the next pass.