DEV Community

Sujith V S
Sujith V S

Posted on • Updated on

break and continue statements in C programming.

break

The break statement in loop is used to terminate from the loop and no further code after for loop will be executed.

break statement in for loop:

int main() {
    for(int i=1; i<=5; i++){
        if(i==3){
            break;
        }
        printf("%d\n", i);
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

break statement in while loop

int main() {

    while(1){
        int number;
        printf("Enter the number: ");
        scanf("%d", &number);

        if(number < 0){
            break;
        }
        printf("%d\n", number);
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

continue

The continue statement skips the current iteration of the loop and starts the loop with next iteration.
Example:

int main() {
    for(int i=1; i<=5; i++){

        if(i==3){
            continue;
        }

        printf("%d\n", i);
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Below is the code using both break and continue statement:

#include <stdio.h>

int main() {

    while(1){
        int number;

        printf("Enter a number: ");
        scanf("%d", &number);

        if(number <= 0){
            break;
        }

        if((number % 2) != 0){
            continue;
        }

        printf("%d\n", number);
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)