Sure! Let's discuss the break
and continue
statements in C using simple language:
The break
statement in C is used to immediately exit from a loop, skipping any remaining code inside the loop. It's commonly used to terminate a loop prematurely when a certain condition is met.
Here's a simple example:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", i);
if (i == 2) {
break; // Exit the loop when i equals 2
}
}
return 0;
}
In this example:
i = 0
to i = 4
.i
.i
becomes 2, the break
statement is encountered, and the loop terminates immediately.So, the output of this code will be:
0
1
2
The continue statement in C is used to skip the remaining code inside a loop and proceed to the next iteration of the loop. It's handy when you want to skip certain iterations based on a condition without terminating the loop entirely.
Here's a simple example:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip the rest of the loop when i equals 2
}
printf("%d\n", i);
}
return 0;
}
In this Examples
i = 0
to i = 4
.i
is equal to 2.i
is equal to 2, the continue
statement is encountered, and the loop proceeds immediately to the next iteration without executing the remaining code inside the loop.i
equals 2, the print statement inside the loop is skippedThe output of this code will be:
0
1
3
4
This is because i equals 2 is skipped due to the continue statement, and the loop continues with the next iteration.