Go Back

break and continue in c language

11/16/2023
All Articles

#break continue in c language

break and continue in c language

Break and continue in c language

break and continue are control flow statements in C (and many other programming languages) that are used in loops (like for, while, and do-while) to alter the normal flow of execution

break Statement:
The innermost loop (for, while, or do-while) can be ended with the break statement, which also moves control to the statement that comes right after the loop is ended. It is frequently used in conjunction with conditional statements to end the loop early in response to a specific circumstance


#include <stdio.h>

int main() {
    // Example using break to exit a loop early
    for (int i = 1; i <= 10; ++i) {
        if (i == 5) {
            printf("Breaking out of the loop at i = 5\n");
            break;  // exit the loop when i equals 5
        }
        printf("%d ", i);
    }

    return 0;
}

continue Statement:
The continue statement is used to move on to the next iteration of a loop and bypass the remaining code for the current iteration.

#include <stdio.h>

int main() {
    // Example using continue to skip an iteration
    for (int i = 1; i <= 5; ++i) {
        if (i == 3) {
            printf("Skipping iteration at i = 3\n");
            continue;  // skip the rest of the loop for i = 3
        }
        printf("%d ", i);
    }

    return 0;
}

Article