Break Statement in C
The break statement in C is used to immediately terminate a loop (such as for, while, or do-while) or a switch statement. When break is encountered, the program exits the loop.
Syntax:
break;
Example 1: break statement in switch
#include <stdio.h> int main() { int day; printf("Enter a number (1-7) for the day of the week: "); scanf("%d", &day); switch (day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default: printf("Invalid input! Please enter a number between 1 and 7.\n"); } return 0; }
Output:
Enter a number (1-7) for the day of the week: 3 Wednesday
Example 2: break statement in for loop
#include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { if (i == 5) { printf("Loop stopped at %d\n", i); break; // Exit the loop when i == 5 } printf("i = %d\n", i); } printf("Loop exited.\n"); return 0; }
Output:
i = 1 i = 2 i = 3 i = 4 Loop stopped at 5 Loop exited.