MODULE 2: C++ BASICS & CONTROL FLOW 2.7 C++ Jump Statements (`break`, `continue`, `goto`) - 10 Real-World Examples

Industrial reference manual: Comprehensive architectural breakdown of C++ jump control statements (`break`, `continue`, `goto`), execution redirection mechanics, and 10 production-aligned real-world code implementations with outputs.

🔀 Mastering C++ Jump Statements: Directing Program Flow

Jump statements unconditionally transfer program control within a function scope. They empower developers to prematurely terminate loops, skip specific iteration cycles, or jump directly to labeled checkpoints.

🛑 Break & Continue

  • break: Terminates the enclosing loop or switch statement immediately, resuming execution after the block.
  • continue: Skips the remaining statements in the current loop iteration and immediately evaluates the next iteration condition.

🎯 Goto Statement

  • goto label: Unconditionally jumps program execution to a user-defined target label within the same function.
  • *Note:* Generally discouraged in modern software engineering due to readability and maintenance risks ("spaghetti code").

📊 End-to-End Jump Control & Redirection Workflow Diagram

1. Loop Execution

Loop iterates over items or numerical sequence.

→

2. Condition Check

Evaluates trigger condition (`targetFound == true`).

→

3. Jump Trigger

Encounter `break`, `continue`, or `goto` instruction.

↓

6. Execution Resumes

Program continues execution past loop or at target label.

←

5. Redirection

Exits loop (`break`), skips iteration (`continue`), or jumps (`goto`).

←

4. State Evaluation

Determines redirection path based on instruction type.

1. `break`: Inventory Database Search Termination
Searches an array for a specific product ID and terminates the loop immediately upon discovery using `break`.
C++ / Inventory Database Search (`break`)
#include <iostream>

using namespace std;

int main() {
    int productCatalog[] = {101, 105, 112, 120, 135};
    int searchTarget = 112;
    bool found = false;

    cout << "--- Database Lookup (Product ID: 112) ---" << endl;
    for (int i = 0; i < 5; i++) {
        cout << "Checking ID: " << productCatalog[i] << endl;
        if (productCatalog[i] == searchTarget) {
            found = true;
            cout << "Match found at index " << i << "!" << endl;
            break; // Terminate loop instantly
        }
    }
    return 0;
}
--- Database Lookup (Product ID: 112) --- Checking ID: 101 Checking ID: 105 Checking ID: 112 Match found at index 2!
2. `continue`: Skipping Out-of-Stock Items in Batch Processing
Processes active inventory items while skipping zero-stock entries using `continue`.
C++ / Out-of-Stock Skips (`continue`)
#include <iostream>

using namespace std;

int main() {
    int stockLevels[] = {12, 0, 45, 0, 8, 30};

    cout << "--- Active Inventory Batch Processing ---" << endl;
    for (int i = 0; i < 6; i++) {
        if (stockLevels[i] == 0) {
            continue; // Skip processing for out-of-stock items
        }
        cout << "Processing item batch with " << stockLevels[i] << " units." << endl;
    }
    return 0;
}
--- Active Inventory Batch Processing --- Processing item batch with 12 units. Processing item batch with 45 units. Processing item batch with 8 units. Processing item batch with 30 units.
3. `break`: ATM PIN Retry Lockout After 3 Failures
Locks the terminal and terminates the login loop immediately when 3 incorrect PIN attempts occur.
C++ / ATM Lockout (`break`)
#include <iostream>

using namespace std;

int main() {
    int correctPin = 9999;
    int attempts = 0;
    int simulatedInputs[] = {1111, 2222, 9999}; // 3rd attempt is correct

    cout << "--- ATM Authentication Terminal ---" << endl;
    while (attempts < 3) {
        int pin = simulatedInputs[attempts];
        attempts++;
        cout << "Attempt " << attempts << " entered: " << pin << endl;

        if (pin == correctPin) {
            cout << "PIN verified successfully. Access granted!" << endl;
            break; // Exit loop upon success
        }

        if (attempts == 3) {
            cout << "[SECURITY ALERT]: Card blocked due to 3 failed attempts!" << endl;
        }
    }
    return 0;
}
--- ATM Authentication Terminal --- Attempt 1 entered: 1111 Attempt 2 entered: 2222 Attempt 3 entered: 9999 PIN verified successfully. Access granted!
4. `continue`: Filtering Out Negative Sensor Reading Anomalies
Ignores faulty negative temperature sensor spikes during weather telemetry logging using `continue`.
C++ / Sensor Anomaly Filtering (`continue`)
#include <iostream>

using namespace std;

int main() {
    int sensorReadings[] = {24, 26, -999, 25, 27, -999, 28}; // -999 represents error spike

    cout << "--- Weather Telemetry Normalizer ---" << endl;
    for (int i = 0; i < 7; i++) {
        if (sensorReadings[i] == -999) {
            continue; // Ignore corrupted sensor readings
        }
        cout << "Logged Temperature: " << sensorReadings[i] << "°C" << endl;
    }
    return 0;
}
--- Weather Telemetry Normalizer --- Logged Temperature: 24°C Logged Temperature: 26°C Logged Temperature: 25°C Logged Temperature: 27°C Logged Temperature: 28°C
5. Nested Loop `break`: Breaking Out of Inner and Outer Loops
Demonstrates how `break` only exits the immediate enclosing loop, requiring a flag or design pattern to exit nested loops.
C++ / Nested Loop Control (`break`)
#include <iostream>

using namespace std;

int main() {
    bool targetFound = false;

    cout << "--- Coordinate Grid Matrix Scan ---" << endl;
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 3; col++) {
            cout << "Scanning coordinate (" << row << ", " << col << ")" << endl;
            if (row == 2 && col == 2) {
                targetFound = true;
                cout << "Target found at matrix sector (2,2)!" << endl;
                break;
            }
        }
        if (targetFound) break; // Break outer loop as well
    }
    return 0;
}
--- Coordinate Grid Matrix Scan --- Scanning coordinate (1, 1) Scanning coordinate (1, 2) Scanning coordinate (1, 3) Scanning coordinate (2, 1) Scanning coordinate (2, 2) Target found at matrix sector (2,2)!
6. `continue`: Skipping Discount Calculations for Blacklisted Accounts
Processes customer loyalty discounts while instantly skipping blacklisted accounts using `continue`.
C++ / Loyalty Discount Filter (`continue`)
#include <iostream>

using namespace std;

int main() {
    bool isAccountBlacklisted[] = {false, false, true, false, true};
    double accountBalances[] = {5000.0, 12000.0, 8000.0, 3000.0, 15000.0};

    cout << "--- Loyalty Bonus Distribution ---" << endl;
    for (int i = 0; i < 5; i++) {
        if (isAccountBlacklisted[i]) {
            continue; // Skip blacklisted accounts
        }
        double bonus = accountBalances[i] * 0.10;
        cout << "Account " << i + 1 << " awarded bonus: ₹" << bonus << endl;
    }
    return 0;
}
--- Loyalty Bonus Distribution --- Account 1 awarded bonus: ₹500.0 Account 2 awarded bonus: ₹1200.0 Account 4 awarded bonus: ₹300.0
7. `break`: First-Come-First-Served Ticket Allocation
Allocates limited concert tickets to eager customers in a queue and stops immediately when seats run out.
C++ / Ticket Allocation (`break`)
#include <iostream>

using namespace std;

int main() {
    int availableTickets = 3;

    cout << "--- Concert Ticket Box Office ---" << endl;
    for (int customerId = 1; customerId <= 10; customerId++) {
        if (availableTickets == 0) {
            cout << "House Full! Stopping ticket sales." << endl;
            break; // Stop issuing tickets
        }
        cout << "Ticket allocated to Customer #" << customerId << endl;
        availableTickets--;
    }
    return 0;
}
--- Concert Ticket Box Office --- Ticket allocated to Customer #1 Ticket allocated to Customer #2 Ticket allocated to Customer #3 House Full! Stopping ticket sales.
8. `continue`: Password Validation Iteration Check
Validates a sequence of password entry attempts, skipping empty keystroke buffers using `continue`.
C++ / Password Input Validation (`continue`)
#include <iostream>
#include <string>

using namespace std;

int main() {
    string attempts[] = {"", "Admin123", "", "SecurePass#1"};

    cout << "--- Password Input Validator ---" << endl;
    for (int i = 0; i < 4; i++) {
        if (attempts[i].empty()) {
            cout << "Attempt " << i + 1 << ": Empty input ignored." << endl;
            continue; // Skip empty attempts
        }
        cout << "Attempt " << i + 1 << ": Validated password string." << endl;
    }
    return 0;
}
--- Password Input Validator --- Attempt 1: Empty input ignored. Attempt 2: Validated password string. Attempt 3: Empty input ignored. Attempt 4: Validated password string.
9. `goto`: Emergency Shutdown Exception Exit
Uses a `goto` statement to jump directly to an emergency shutdown cleanup block from deep inside nested loops.
C++ / Emergency Shutdown (`goto`)
#include <iostream>

using namespace std;

int main() {
    bool emergencyTriggered = true;

    cout << "--- Industrial Reactor Monitoring ---" << endl;
    for (int core = 1; core <= 3; core++) {
        for (int sector = 1; sector <= 3; sector++) {
            if (core == 2 && sector == 2 && emergencyTriggered) {
                goto EMERGENCY_SHUTDOWN; // Jump directly to cleanup label
            }
        }
    }

    EMERGENCY_SHUTDOWN:
    cout << "[CRITICAL]: Emergency shutdown sequence initiated. Cooling valves opened!" << endl;
    return 0;
}
--- Industrial Reactor Monitoring --- [CRITICAL]: Emergency shutdown sequence initiated. Cooling valves opened!
10. `break`: Early Exit on Finding Target Prime Number
Scans an array of integers and terminates search execution immediately upon finding the first prime number.
C++ / First Prime Search (`break`)
#include <iostream>

using namespace std;

int main() {
    int numbers[] = {4, 6, 8, 11, 14, 18}; // 11 is the first prime

    cout << "--- First Prime Number Search ---" << endl;
    for (int i = 0; i < 6; i++) {
        int num = numbers[i];
        bool isPrime = true;

        if (num <= 1) continue;

        for (int j = 2; j <= num / 2; j++) {
            if (num % j == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            cout << "First prime number discovered: " << num << endl;
            break; // Stop scanning once found
        }
    }
    return 0;
}
--- First Prime Number Search --- First prime number discovered: 11