How to terminate a loop statement early in C language?

In C programming language, the break statement can be used to prematurely terminate a loop statement.

The break statement can be used in for loops, while loops, and do-while loops. When the break statement is executed, the program will immediately exit the current loop and continue with the code after the loop.

Here is an example of using the break statement to terminate a loop early:

#include <stdio.h>

int main() {
    int i;
    for (i = 1; i <= 10; i++) {
        if (i == 5) {
            break; // 当 i 等于 5 时提前终止循环
        }
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

The output is:

1 2 3 4

In the above example, the break statement is executed when i equals 5, causing the loop to break, so only 1, 2, 3, and 4 will be printed.

bannerAds