C++ Break & Continue

Concept about jump statements.

* We didn't include the goto statement (Available in C) in the C++ course cause it's an unconditional jump statement, and It can make the code more error-prone and difficult to understand.

Jump Statements

Jump statements are used to alter the normal flow of control in a program. There are three main jump statements in C++:

The 'break' and 'continue' statements are often referred to as "control flow" statements rather than "jump" statements, but they do control the flow of a program's execution.

break Statement:

The break statement is used in C++ to exit a loop prematurely, before the loop condition is false. It is commonly used in 'for', 'while', and 'do-while' loops. When a 'break' statement is encountered, the control flow immediately exits the loop, and the program continues with the statement following the loop.

Here's a simple example using a 'for' loop:

cpp Copy Code
#include<iostream>

int main() {
    for (int i = 0; i < 10; ++i) {
        std::cout << i << " ";
        if (i == 5) {
            break; // Exit the loop when i reaches 5
        }
    }

    std::cout << "\nAfter the loop.\n";

    return 0;
}

The loop will print numbers from 0 to 5. When 'i' becomes 5, the 'break' statement is encountered, and the loop is exited.

Output:
0 1 2 3 4 5 
After the loop.

Note: It's generally considered good practice to use 'break' sparingly and to have clear conditions for its use.

continue Statement:

The continue statement in C++ is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration of the loop. It is often used to bypass certain code blocks based on a specific condition.

Here's a simple example using a 'for' loop:

cpp Copy Code
#include<iostream>

int main() {
    for (int i = 0; i < 5; ++i) {
        if (i == 2) {
            continue; // Skip the rest of the loop for i = 2
        }
        std::cout << i << " ";
    }

    std::cout << "\nAfter the loop.\n";

    return 0;
}

when 'i' is equal to 2, the 'continue' statement is encountered, and the loop proceeds to the next iteration without executing the remaining statements inside the loop for the current iteration.

Output:
0 1 3 4 
After the loop.

Note: It allows you to avoid the execution of the remaining code for that iteration, and overusing 'continue' can make code more complex and harder to understand.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.