C Break and Continue
Break
C programming language, break and continue are control flow statements that alter the normal flow of execution within loops (such as for, while, and do-while) and switch statements.
break and continue are two control flow statements used within loops to alter their execution.
This example jumps out of the for loop when i is equal to 4:
Example
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("%d\n", i);
}
return 0;
}
Output
0
1
2
3
TThe continue statement is used within loops (for, while, do-while) to skip the remaining statements in the current iteration of the loop and immediately move to the next iteration.
Here's a simple example using a loop::
Example
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
}
return 0;
}
Output
0
1
2
3
4
5
6
7
8
9
Break and Continue in While Loop
You can also use break and continue in while loops:
Break Example
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
if (i == 4) {
break;
}
printf("%d\n", i);
i++;
}
return 0;
}
Output
0
1
2
3
Continue Example
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
printf("%d\n", i);
i++;
}
return 0;
}
Output
0
1
2
3
4
5
6
7
8
9