In the C programming language, break
and continue
are two control flow statements used within loops (e.g., for
, while
, do-while
) to control the flow of the program. They serve different purposes:
1. break
statement:
The break
statement is used to exit a loop prematurely. When a break
statement is encountered inside a loop, it immediately terminates the loop and the program continues with the next statement after the loop. This is often used to exit a loop early if a certain condition is met.
#include
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf("%d ", i);
}
return 0;
}
In this example, the loop will terminate when i
equals 5, so only the numbers 1 through 4 will be printed.
2. continue
statement:
The continue
statement is used to skip the rest of the current iteration and jump to the next iteration of a loop. It is often used when you want to skip certain loop iterations based on a condition without exiting the entire loop.
#include
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}
In this example, the continue
statement is used to skip even numbers. So, only the odd numbers 1, 3, 5, 7, and 9 will be printed.
Both break
and continue
are powerful tools for controlling the flow of your loops, allowing you to make your code more efficient and responsive to specific conditions. They are commonly used in a variety of loop structures to create precise control over the iteration process.