C break Statement

The break statement ends the nearest loop or switch immediately. The program continues with the line after the loop.

Stop a loop when a value is found

#include <stdio.h>

int main(void) {
    int marks[] = {45, 60, 38, 72, 90};

    for (int i = 0; i < 5; i++) {
        if (marks[i] < 40) {
            printf("First failed mark is %d at index %d\n", marks[i], i);
            break;
        }
    }
    printf("Done\n");
    return 0;
}

Output:

Output of the above program is

First failed mark is 38 at index 2
Done

Without break the loop would check the remaining marks also, which is not needed.

break in a nested loop

In nested loops, break stops only the inner loop in which it is written.

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (j == 2) break;
            printf("i=%d j=%d\n", i, j);
        }
    }
    return 0;
}

Output:

Output of the above program is

i=1 j=1
i=2 j=1
i=3 j=1

Note: To leave many loops at once you can use a flag variable, a function with return, or goto (see goto).

Next: C continue Statement.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.