Break and Continue

The break statement terminates a loop, and continue skips the rest of the code in the loop.

Break Statement

The break statement is used to terminate a loop. It stops the execution of the loop and transfers the control to the next statement following the loop.

Example:1

#include <stdio.h>
int main() {
    for (int i = 0; i < 5; i++) {
        if (i == 3) 
        break;
        printf("%d\n", i);
    }
    printf("Loop exited.\n");
    return 0;
}

Output

0 1 2 Loop exited.

Example 2: Using break in a while Loop

#include <stdio.h>
int main() {
    while (i <= 10) {
        if (i == 5) {
            break;  // Exit the loop when i is 5
        }
        printf("%d\n", i);
        i++;
    }
    printf("Loop exited.\n");
    return 0;
}

Output

1 2 3 4 Loop exited.

Example 3: Using break in a do-while Loop

#include <stdio.h>
int main() {
    int i = 1;
    do {
        if (i == 5) {
            break;  // Exit the loop when i is 5
        }
        printf("%d\n", i);
        i++;
    } while (i <= 10);
    printf("Loop exited.\n");
    return 0;
}

Output

1 2 3 4 Loop exited.

Example 4: Using break in a switch Statement

#include <stdio.h>
int main() {
    int choice;
    printf("Enter a number (1-3): ");
    scanf("%d", &choice);
    switch (choice) {
        case 1:
            printf("Option 1 selected.\n");
            break;  // Exit the switch block
        case 2:
            printf("Option 2 selected.\n");
            break;
        case 3:
            printf("Option 3 selected.\n");
            break;
        default:
            printf("Invalid option.\n");
    }

    return 0;
}

Output

Enter a number (1-3): 2 Option 2 selected.

Continue Statement

The continue statement in C is used to skip the rest of the code in the current iteration of a loop and proceed directly to the next iteration. It is typically used to bypass certain parts of the loop when a specific condition is met, without terminating the loop.

Example 1: Using continue in a for loop.

#include <stdio.h>
int main() {
    for (int i = 0; i < 5; i++) {
        if (i == 2) 
        continue;  // Skips the itereation when i is 2
        printf("%d\n", i);
    }
    return 0;
}

Output

0 1 3 4

Example 2: Using continue in a while loop.

#include <stdio.h>
int main() {
    int i = 1;
    while (i <= 5) {
        if (i == 3) {
            i++;  // Increment before continue to avoid infinite loop
            continue;  // Skip the iteration when i is 3
        }
        printf("%d\n", i);
        i++;
    }
    return 0;
}

Output

1 2 4 5

Example 3: Using continue in a do-while loop.

#include <stdio.h>
int main() {
    int i = 1;
    do {
        if (i == 3) {
            i++;  // Increment before continue to avoid infinite loop
            continue;  // Skip the iteration when i is 3
        }
        printf("%d\n", i);
        i++;
    } while (i <= 5);
    return 0;
}

Output

1 2 4 5