Sometimes you need to alter the flow of a loop by either stopping it entirely or skipping an iteration.
break StatementYou have already seen the break statement used in an earlier chapter of this tutorial (in the switch statement). It can also be used to jump out of a loop.
for (int i = 0; i < 10; i++) {
if (i == 4) {
break; // Loop stops when i is 4
}
cout << i << "\n";
}
continue StatementThe continue statement breaks one iteration in the loop (if a specified condition occurs), and continues with the next iteration in the loop.
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue; // Skips the rest of the loop block when i is 4
}
cout << i << "\n";
}
These two statements give you precise control over how your loops behave in real-time scenarios.
Which statement is used to skip the rest of the current loop iteration and move to the next one?