In C programming, the "break" statement is used to terminate the execution of a loop (such as "for", "while", or "do-while" loops) or a "switch" statement prematurely.
When encountered, the "break" statement causes the program to exit the loop or switch block immediately, bypassing any remaining code inside it.
Here's a basic example demonstrating the usage of "break" in a "for" loop:
#include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { if (i == 5) { break; // Terminate the loop when i equals 5 } printf("%d\n", i); } printf("Loop exited early because of break statement.\n"); return 0; }
0 1 2 3 4 Loop exited early because of break statement.
the loop terminates prematurely when "I" equals 5 due to the "break" statement. The program then proceeds to execute the code after the loop.
Similarly, "break" can be used inside a "switch" statement to exit the switch block.
Here's an example:
#include <stdio.h> int main() { int choice = 2; switch (choice) { case 1: printf("Choice is 1\n"); break; case 2: printf("Choice is 2\n"); break; // This break causes the switch block to terminate early case 3: printf("Choice is 3\n"); break; default: printf("Invalid choice\n"); } printf("Switch block exited early because of break statement.\n"); return 0; }
Choice is 2 Switch block exited early because of break statement.
since "choice" is 2, the "case 2" is executed, and the "switch" block is exited immediately after that due to the break statement.
#include <stdio.h> int main() { int i = 1; while (1) { if (i > 5) { break; // Exit the loop when i exceeds 5 } printf("%d ", i); i++; } printf("\nLoop exited early because of break statement.\n"); return 0; }
1 2 3 4 5 Loop exited early because of break statement.
Note: the "while" loop prints numbers from 1 to 5 and then terminates when i exceeds 5 due to the "break" statement.