In C programming, the break statement is a control statement that allows you to exit a loop prematurely. It is commonly used in for, while, and do-while loops, as well as in switch statements.
When the break statement is encountered inside a loop, the loop is immediately terminated, and program execution continues at the next statement following the loop. This means that any remaining iterations of the loop are skipped, and the program moves on to execute the next statement after the loop.
Here’s an example of using the break statement in a while loop:
int i = 0;
while (i < 10) {
if (i == 5) {
break;
}
printf("%d ", i);
i++;
}
printf("Loop terminated.\n");
In this example, the while loop will iterate until i reaches 5. At that point, the break statement is executed, and the loop is terminated. The program then moves on to execute the printf statement outside of the loop, which prints “Loop terminated.” to the console.
The output of this program will be:
0 1 2 3 4 Loop terminated.