In C programming, the break
statement is used to exit a loop prematurely or to exit a switch
statement.
#include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { if (i == 5) { break; // Exit the loop when i is 5 } printf("%d ", i); } return 0; }
1 2 3 4
In this example, the program will print numbers from 1 to 4 and then exit the loop when i
becomes 5 because of the break
statement.
#include <stdio.h> int main() { int choice = 2; switch (choice) { case 1: printf("Option 1 selected\n"); break; case 2: printf("Option 2 selected\n"); break; // Exit the switch statement after printing this line case 3: printf("Option 3 selected\n"); break; default: printf("Invalid choice\n"); } return 0; }
Option 2 selected
In this example, because choice
is set to 2, the program will print "Option 2 selected" and then exit the switch
statement due to the break
statement.