Cpp Break and continue

In C++, the break and continue statements are control flow statements that allow you to alter the flow of execution in loops, such as for, while, and do-while loops. These statements are used to control how the program behaves within a loop.

1. break statement:

a. The break statement is used to exit the current loop prematurely. When the break statement is encountered inside a loop, the loop is immediately terminated, and the program continues with the next statement after the loop. This is useful when you want to exit a loop based on a certain condition.

        
#include 
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            cout << "Breaking the loop at i = 5." << endl;
            break;
        }
        cout << "i = " << i << endl;
    }

    cout << "Loop finished." << endl;
    return 0;
}
        
    

b. In this example, the loop will terminate when i is equal to 5, and the program will print "Breaking the loop at i = 5." and "Loop finished."

2. continue statement:

a. The continue statement is used to skip the current iteration of a loop and continue with the next iteration. When the continue statement is encountered inside a loop, the current iteration is aborted, and the program proceeds with the next iteration of the loop.

        
#include 
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            cout << "Skipping iteration at i = 3." << endl;
            continue;
        }
        cout << "i = " << i << endl;
    }

    cout << "Loop finished." << endl;
    return 0;
}
        
    

b. In this example, when i is equal to 3, the continue statement is executed, and the program skips the iteration for i = 3. The output will be:

i = 1
i = 2
Skipping iteration at i = 3.
i = 4
i = 5
Loop finished.