C Break

The break statement is a control flow statement used to exit from loops or switch statements prematurely. It provides a way to terminate the loop or switch block before its normal termination condition is met.

Syntax:

// Inside a loop or switch case
break;

Usage

1. break with Loops

The break statement can be used within for, while, and do-while loops to terminate the loop and transfer control to the statement immediately following the loop.

Example 1: Using break in a for loop

#include <stdio.h>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            break; // Exit the loop when i is 5
        }
        printf("i = %d\\n", i);
    }
    printf("Loop terminated.\\n");
    return 0;
}

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
Loop terminated.

Example 2: Using break in a while loop

#include <stdio.h>

int main() {
    int count = 0;
    while (1) { // Infinite loop
        if (count == 3) {
            break; // Exit the loop when count is 3
        }
        printf("count = %d\\n", count);
        count++;
    }
    printf("Loop terminated.\\n");
    return 0;
}

Output:

count = 0
count = 1
count = 2
Loop terminated.

2. break with switch Case

In a switch statement, the break statement is used to terminate a particular case and prevent the execution from falling through to subsequent cases.

Example:

#include <stdio.h>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\\n");
            break;
        case 2:
            printf("Tuesday\\n");
            break;
        case 3:
            printf("Wednesday\\n");
            break;
        case 4:
            printf("Thursday\\n");
            break;
        case 5:
            printf("Friday\\n");
            break;
        default:
            printf("Weekend\\n");
            break;
    }

    return 0;
}

Output:

Wednesday

Important Considerations

Scope of break: The break statement only affects the loop or switch block in which it is used.

Termination of Execution: If a break statement is used within a switch statement, it stops the execution of that case block.

Nested Loops: To exit from multiple nested loops, you might use additional logic or a flag variable.