Break and Continue Statement

0 nanniematthias November 25, 2020

Break Statement:

The breakstatement terminates the execution of the loop and the control is transferred to the statement immediately following the loop. Generally, the loop is terminated 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 breakstatements in the switchstatement which causes a transfer of control out of the entire switchstatement, to the first statement following the switch statement. The switch statement will be discussed in the next chapter.

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

#include <stdio.h>

int main(){

    int x;

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

    return 0;
}

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 is to be executed 10 times (i.e. 1 to 10). But the use of breakstatement within the body of the loophas 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 continuestatement is used 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 skipped 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;
}

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 is executed so that the print statement is not executed. The continue statement to bypass the print statement following the continue statement and the loop is executed for the next pass.