break: Terminates the execution of a loop or switch statement and transfers control to the statement immediately following the loop or switch.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}cout << i << ” “;
}
continue: Skips the rest of the loop’s code block for the current iteration and moves to the next iteration of the loop.
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip printing 2
}
cout << i << ” “;
}
In the above examples, break
is used to exit the loop prematurely when a condition is met, while continue
is used to skip the rest of the loop’s code block for a specific iteration. These control flow statements enhance the flexibility and efficiency of your code by altering the execution flow as needed.