Break Statement in C
Hello Everyone, In this article, we will cover the concept of Break Statement in C Programming. In this topic we will cover its syntax, how it works, and practical examples of its use. Whether you’re new to C or have some experience, this guide will help you to understand Break Statement in C effectively. Let’s get started.
The “break statement” is a control flow statement in C programming languages that is used to exit a loop or switch statement. When encountered, it causes the loop or switch statement to immediately terminate, and control flow continues with the statement following the loop or switch.
Example of a “for” loop that uses a “break” statement to terminate the loop early
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
// do some work here
}
In this example, the loop will run 10 times, but when “i” reaches a value of 5, the “break” statement is encountered, causing the loop to terminate early. Any remaining iterations are skipped, and control flow continues with the statement following the loop.
Example of a “switch” statement that uses a “break” statement to exit early
int x = 2;
switch (x) {
case 1:
// do something for case 1
break;
case 2:
// do something for case 2
break;
case 3:
// do something for case 3
break;
default:
// do something for default case
break;
}
In this example, the “switch” statement checks the value of “x” and executes the code for the appropriate case. However, when the correct case is found (in this case, case 2), the “break” statement is encountered, causing the switch statement to exit early. Any remaining cases are skipped, and control flow continues with the statement following the switch.
C Progam to explain break statement
#include <stdio.h>
int main() {
int i;
// Loop from 1 to 10
for (i = 1; i <= 10; i++) {
// If i is equal to 5, break out of the loop
if (i == 5) {
printf("Breaking out of the loop at i = %d\\n", i);
break;
}
// Otherwise, print the current value of i
printf("%d ", i);
}
// Print a message indicating that the loop has ended
printf("\\nLoop ended\\n");
return 0;
}
When you run this program, it will output the following:
1 2 3 4 Breaking out of the loop at i = 5
Loop ended
As you can see, the program uses a “for” loop to count from 1 to 10. Inside the loop, there’s an “if” statement that checks whether the current value of “i” is equal to 5. If it is, the program prints a message saying that it’s breaking out of the loop, and then uses the “break” statement to exit the loop early.
Because the “break” statement is encountered when “i” is equal to 5, the loop ends early and the program skips over the remaining iterations. After the loop is finished, the program prints a message indicating that the loop has ended.