C break statement
Created By: chatGPT
The break statement in C is used to exit from a loop or a switch statement prematurely. It allows the program to jump to the next statement following the loop or switch block. This is particularly useful when a condition is met, and you want to stop further iterations or actions. Here's how it can be implemented across different scenarios.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exits the loop when i is 5
}
printf("%d\n", i);
}
In the example above, the loop prints numbers from 0 to 4. When
i
becomes 5, the break statement is executed, and the loop terminates. It is also possible to use the break statement in nested loops, but it will only exit from the innermost loop where it is called.for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break; // exits the inner loop when i is 1 and j is 1
}
printf("i: %d, j: %d\n", i, j);
}
}
In this nested loop example, when
i
is 1 and j
is 1, the inner loop exits, but the outer loop continues. Thus, the printed output will be all combinations of i
and j
until the inner loop is interrupted by the break statement.// Switch statement example
int day = 3;
switch(day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
In the switch statement example, depending on the value of
day
, it will print the corresponding day of the week. The break statement is crucial here because it prevents the execution from falling through to subsequent cases, thus ensuring only the matched case is executed.#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("%d\n", i);
}
return 0;
}