Yes, break and continue can be used with nested loops. When used within nested loops, break terminates only the innermost loop, while continue moves to the next iteration of the innermost loop.
Here's an example that demonstrates the usage of break and continue in nested loops:
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; i++) {
printf("Outer loop: %d\n", i);
for (j = 1; j <= 3; j++) {
if (j == 2) {
continue; // Skip the rest of the current iteration in the inner loop when j is 2
}
if (i == 2 && j == 3) {
break; // Terminate the inner loop when i is 2 and j is 3
}
printf("Inner loop: %d\n", j);
}
}
return 0;
}
Output:
Outer loop: 1
Inner loop: 1
Inner loop: 3
Outer loop: 2
Inner loop: 1
Outer loop: 3
Inner loop: 1
Inner loop: 3
In this example, the outer loop runs from 1 to 3, and the inner loop runs from 1 to 3 for each iteration of the outer loop. When j is 2 in the inner loop, the continue statement is encountered, skipping the rest of the inner loop body. When i is 2 and j is 3, the break statement is encountered, terminating the inner loop.