Break and Continue in C programming

 Break and Continue in C programming:-

Today we will learn about break and continue statements in c programming. These statement are called uncontrolled statements and it includes the goto statement also. As we have learnt about loops(while, do-while and for loops) there we can use these statements and in switch case we have to use the break statement otherwise if we don't use the break statement it will execute all the cases after the particular case is executed.

Break and Continue statements in C programming
Break and Continue in C programming

First Learn:- Switch case, while loop and for loop.

so first we will learn break statement.

Break:-

The break statements is used to terminate the loop, it can be used in any of the loops and also used in the switch case. when the program is executing a loop or a switch case and if encounter the break statement then it will terminate that block and execute the next instruction.

Syntax:-  break;


Lets see few examples on break

Example1:- 

If a while loop is running 10 times and for some reason if we want to exit from the loop if i becomes greater 5 then we can use the break statement as follows

#include <stdio.h>

int main()
{
    int i=0;
    while(i<10){
        if(i>5)
            break;
        printf("%d.Break has not executed\n", i);
        i++;
    }

    return 0;
}



Output:-

1.Break has not executed
2.Break has not executed
3.Break has not executed
4.Break has not executed
5.Break has not executed

Example2:- 

We can use it in the for loop as well, if we want to break if i becomes equal to 6 then we use break as shown blow

#include <stdio.h>

int main()
{
    for(int i=0; i<15; i++){
        if(i==6)
            break;
        printf("%d ", i);
    }

    return 0;
}


Output:-

0 1 2 3 4 5

Continue:-

We use continue statement if we want to skip a particular iteration of loop and continue with the next iteration. 

Syntax:- continue;

Example1:- 

Lets say we want to print the 10 numbers from 1 to 10 but we do not want to print the number 6, so there we can use the continue statement as shown below


#include <stdio.h>

int main()
{
    
    for(int i=0; i<20; i++){
        if(i==11){
            continue;
        }
        printf("%d ", i);
    }

    return 0;
}

Output:-

0 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 

Example2:- 

Again another similar example using the while loop


#include <stdio.h>

int main()
{
    int i=0;
    while(i<15){
        if(i==10){
            continue;
        }
        printf("%d ", i);
        i++;
    }

    return 0;
}

Output:-

0 1 2 3 4 5 6 7 8 9 11 12 13 14

Post a Comment

0 Comments