MODULE 2: C++ BASICS & CONTROL FLOW 2.6 C++ Loops (`for`, `while`, `do-while`) - 10 Real-Time Examples

Industrial reference manual: Comprehensive architectural breakdown of C++ iteration constructs (`for`, `while`, `do-while`), loop control flow statements (`break`, `continue`), and 10 production-aligned real-time code implementations with outputs.

🔄 Mastering C++ Iteration Constructs: Automating Repetitive Tasks

Loops are control structures used to execute a block of code repeatedly until a specific termination condition is met. They eliminate code redundancy and are essential for iterating through data structures, processing user requests, and managing simulations.

🔁 Iteration Constructs

  • for loop: Ideal when the exact number of iterations is known in advance.
  • while loop: Evaluates condition *before* executing the loop body (entry-controlled).
  • do-while loop: Executes the body *at least once* before checking the condition (exit-controlled).

🛑 Loop Control Statements

  • break: Instantly terminates the loop, jumping control outside.
  • continue: Skips the current iteration and jumps directly to the next loop cycle.

📊 End-to-End Loop Execution & Control Flow Workflow Diagram

1. Initialization

Initialize loop counter variable (`int i = 0`).

→

2. Condition Evaluation

Check boolean termination condition (`i < 10`).

→

3. Loop Body Execution

Execute statements inside braces (or single iteration block).

↓

6. Loop Exit

Condition becomes false; program resumes execution below loop.

←

5. Repeat Cycle

Return to condition check for the next iteration cycle.

←

4. Update / Increment

Increment or decrement loop counter (`i++`).

1. `for` Loop: E-Commerce Shopping Cart Item Subtotal Summation
Uses a standard `for` loop to iterate through an array of item prices and compute the total cart subtotal.
C++ / Shopping Cart Subtotal Summation
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double itemPrices[] = {450.50, 1200.00, 325.25, 850.00};
    int numItems = 4;
    double cartSubtotal = 0.0;

    for (int i = 0; i < numItems; i++) {
        cartSubtotal += itemPrices[i];
    }

    cout << "--- E-Commerce Cart Summary ---" << endl;
    cout << "Total Items in Cart : " << numItems << endl;
    cout << "Calculated Subtotal : ₹" << fixed << setprecision(2) << cartSubtotal << endl;
    return 0;
}
--- E-Commerce Cart Summary --- Total Items in Cart : 4 Calculated Subtotal : ₹2825.75
2. `while` Loop: Rocket Launch Countdown Timer
Uses a `while` loop to execute a countdown sequence from 5 down to 1 before blast-off.
C++ / Rocket Countdown Timer
#include <iostream>

using namespace std;

int main() {
    int countdownSeconds = 5;

    cout << "--- Aerospace Launch Control ---" << endl;
    while (countdownSeconds > 0) {
        cout << "T-Minus " << countdownSeconds << " seconds..." << endl;
        countdownSeconds--;
    }
    cout << "BLAST OFF! Rocket successfully launched into orbit." << endl;
    return 0;
}
--- Aerospace Launch Control --- T-Minus 5 seconds... T-Minus 4 seconds... T-Minus 3 seconds... T-Minus 2 seconds... T-Minus 1 seconds... BLAST OFF! Rocket successfully launched into orbit.
3. `do-while` Loop: ATM PIN Security Verification Retry
Uses a `do-while` loop to ensure the security prompt executes at least once before checking PIN correctness.
C++ / ATM PIN Security Prompt
#include <iostream>

using namespace std;

int main() {
    int correctPin = 4321;
    int enteredPin = 1234; // Simulated incorrect attempt followed by correct
    int attempts = 0;

    cout << "--- ATM Security Terminal ---" << endl;
    do {
        attempts++;
        // Simulating user input update for demo
        if (attempts == 2) enteredPin = 4321; 
        
        cout << "Attempt " << attempts << " - PIN entered: " << enteredPin << endl;
        if (enteredPin != correctPin) {
            cout << "Incorrect PIN. Try again." << endl;
        }
    } while (enteredPin != correctPin && attempts < 3);

    if (enteredPin == correctPin) {
        cout << "Access Granted! Welcome to your account." << endl;
    } else {
        cout << "Card Blocked due to too many failed attempts." << endl;
    }
    return 0;
}
--- ATM Security Terminal --- Attempt 1 - PIN entered: 1234 Incorrect PIN. Try again. Attempt 2 - PIN entered: 4321 Access Granted! Welcome to your account.
4. `for` Loop: Compound Interest Investment Growth (5 Years)
Calculates annual investment compounding growth over a 5-year period using a `for` loop.
C++ / Compound Interest Growth
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double principal = 100000.00;
    double annualRate = 0.08; // 8% return
    int totalYears = 5;

    cout << "--- 5-Year Investment Growth Projection ---" << endl;
    for (int year = 1; year <= totalYears; year++) {
        principal += (principal * annualRate);
        cout << "Year " << year << " Value: ₹" << fixed << setprecision(2) << principal << endl;
    }
    return 0;
}
--- 5-Year Investment Growth Projection --- Year 1 Value: ₹108000.00 Year 2 Value: ₹116640.00 Year 3 Value: ₹125971.20 Year 4 Value: ₹136048.90 Year 5 Value: ₹146932.81
5. `while` Loop with `break`: IoT Sensor Telemetry Polling
Polls an industrial temperature sensor in a `while` loop, breaking instantly when an overheat alert is detected.
C++ / Sensor Telemetry Polling
#include <iostream>

using namespace std;

int main() {
    int pollCycle = 0;
    int sensorReadings[] = {45, 52, 60, 88, 70}; // 88 triggers overheat

    cout << "--- Industrial Sensor Polling ---" << endl;
    while (pollCycle < 5) {
        int currentTemp = sensorReadings[pollCycle];
        cout << "Cycle " << pollCycle + 1 << " - Temperature: " << currentTemp << "°C" << endl;
        
        if (currentTemp >= 80) {
            cout << "[CRITICAL ALERT]: Overheat threshold breached! Shutting down system." << endl;
            break; // Exit loop immediately
        }
        pollCycle++;
    }
    return 0;
}
--- Industrial Sensor Polling --- Cycle 1 - Temperature: 45°C Cycle 2 - Temperature: 52°C Cycle 3 - Temperature: 60°C Cycle 4 - Temperature: 88°C [CRITICAL ALERT]: Overheat threshold breached! Shutting down system.
6. `for` Loop with `continue`: Even Number Batch Processing
Iterates through numbers 1 to 10, using `continue` to skip odd numbers and process only even transaction IDs.
C++ / Even Number Batch Filter
#include <iostream>

using namespace std;

int main() {
    cout << "--- Batch Processing Even IDs ---" << endl;
    for (int id = 1; id <= 10; id++) {
        // If ID is odd, skip this iteration
        if (id % 2 != 0) {
            continue;
        }
        cout << "Processing batch ID: " << id << endl;
    }
    return 0;
}
--- Batch Processing Even IDs --- Processing batch ID: 2 Processing batch ID: 4 Processing batch ID: 6 Processing batch ID: 8 Processing batch ID: 10
7. Nested `for` Loop: Multiplication Table Generator
Uses nested `for` loops to generate a formatted multiplication table for retail pricing matrices.
C++ / Multiplication Matrix Generator
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    cout << "--- Pricing Tier Matrix (1 to 3) ---" << endl;
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 5; j++) {
            cout << setw(4) << (i * j) << " ";
        }
        cout << endl;
    }
    return 0;
}
--- Pricing Tier Matrix (1 to 3) --- 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15
8. `for` Loop: Prime Number Primality Test
Tests whether a given number is prime using trial division inside a `for` loop.
C++ / Prime Number Validator
#include <iostream>

using namespace std;

int main() {
    int targetNumber = 29;
    bool isPrime = true;

    if (targetNumber <= 1) isPrime = false;

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

    cout << "--- Cryptographic Primality Test ---" << endl;
    cout << "Target Number : " << targetNumber << endl;
    cout << "Is Prime?     : " << (isPrime ? "YES (Secure)" : "NO (Composite)") << endl;
    return 0;
}
--- Cryptographic Primality Test --- Target Number : 29 Is Prime? : YES (Secure)
9. `do-while` Loop: Interactive Menu-Driven POS System
Simulates a Point-of-Sale (POS) menu that repeats until the cashier selects the exit option.
C++ / Menu-Driven POS System
#include <iostream>

using namespace std;

int main() {
    int choice = 1;
    int transactionCount = 0;

    cout << "--- POS Terminal Session ---" << endl;
    do {
        transactionCount++;
        // Simulated menu choice: process 2 transactions then exit
        if (transactionCount == 3) {
            choice = 3; // Exit code
        }

        cout << "[Menu] 1. New Sale | 2. Refund | 3. Exit" << endl;
        cout << "Cashier selected option: " << choice << endl;

        if (choice == 1) {
            cout << "-> Processing sale transaction..." << endl;
        } else if (choice == 2) {
            cout << "-> Processing refund..." << endl;
        } else if (choice == 3) {
            cout << "-> Closing terminal session." << endl;
        }
    } while (choice != 3);

    return 0;
}
--- POS Terminal Session --- [Menu] 1. New Sale | 2. Refund | 3. Exit Cashier selected option: 1 -> Processing sale transaction... [Menu] 1. New Sale | 2. Refund | 3. Exit Cashier selected option: 1 -> Processing sale transaction... [Menu] 1. New Sale | 2. Refund | 3. Exit Cashier selected option: 3 -> Closing terminal session.
10. `for` Loop: Factorial Calculation for Probability Statistics
Computes the factorial of a number ($n!$) required for statistical permutation and combination formulas.
C++ / Factorial Calculator
#include <iostream>

using namespace std;

int main() {
    int n = 6;
    long long factorialResult = 1;

    for (int i = 1; i <= n; i++) {
        factorialResult *= i;
    }

    cout << "--- Statistical Permutation Calculator ---" << endl;
    cout << "Number (n)      : " << n << endl;
    cout << "Factorial (n!)  : " << factorialResult << endl;
    return 0;
}
--- Statistical Permutation Calculator --- Number (n) : 6 Factorial (n!) : 720