C++ - Break & Continue

In C++, the break and continue statements are used to control the flow of loops. They allow you to alter the normal execution of a loop based on certain conditions. Here's a brief explanation of both statements:

break statement:

The break statement is used to immediately terminate the execution of a loop. When encountered within a loop, it causes the program to exit the loop and resume execution at the next statement after the loop. It is commonly used to exit a loop prematurely when a specific condition is met. Here's an example:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break;
    }
    std::cout << "Count: " << i << std::endl;
}

In this example, the break statement is encountered when i is equal to 3. As a result, the loop is immediately terminated, and the remaining iterations are skipped.

continue statement:

The continue statement is used to skip the rest of the current iteration of a loop and move on to the next iteration. When encountered within a loop, it causes the program to jump to the next iteration, skipping any code that follows it within the current iteration. It is commonly used to skip certain iterations based on specific conditions. Here's an example:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    std::cout << "Count: " << i << std::endl;
}

In this example, the continue statement is encountered when i is equal to 3. As a result, the current iteration is skipped, and the loop proceeds to the next iteration.