0
0
Cprogramming~5 mins

Break statement in C

Choose your learning style9 modes available
Introduction

The break statement stops a loop or switch early. It helps you exit when you find what you want or need to stop.

When searching for a value in a list and you want to stop once found.
When you want to exit a loop if a certain condition happens.
When you want to stop checking cases in a switch statement after a match.
When you want to avoid unnecessary work inside loops.
When you want to improve program speed by stopping early.
Syntax
C
break;

The break statement is just the word break followed by a semicolon.

It can only be used inside loops (for, while, do-while) or switch statements.

Examples
This loop prints numbers from 0 to 4. When i becomes 5, the break stops the loop.
C
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    printf("%d\n", i);
}
This while loop prints numbers 0, 1, 2 and stops when i is 3.
C
int i = 0;
while (i < 10) {
    if (i == 3) {
        break;
    }
    printf("%d\n", i);
    i++;
}
In this switch, break stops the code from running into the next case.
C
switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    default:
        printf("Other day\n");
        break;
}
Sample Program

This program prints numbers from 1 to 6. When i reaches 7, the break stops the loop early.

C
#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 7) {
            break;
        }
        printf("Number: %d\n", i);
    }
    printf("Loop stopped at 7.\n");
    return 0;
}
OutputSuccess
Important Notes

Using break can make your code faster by stopping loops early.

Be careful not to overuse break; sometimes it can make code harder to read.

Break only exits the closest loop or switch it is inside.

Summary

The break statement stops loops or switch cases immediately.

It is useful to exit early when a condition is met.

Remember to use break only inside loops or switch statements.