Skip to content

C++ Loops

Overview

Loops are fundamental control structures in programming that allow programs to repeat a block of code until a specific condition is met. C++ provides three main types of loops: for loops, while loops, and do-while loops.

🔄 Loop Types Overview

mermaid
graph TD
    A[C++ Loops] --> B[for loop]
    A --> C[while loop]
    A --> D[do-while loop]
    
    B --> B1[Basic for loop]
    B --> B2[Range-based for loop]
    
    C --> C1[Condition checked at start]
    
    D --> D1[Condition checked at end]
    D --> D2[Executes at least once]

📊 for Loop

Basic for Loop Syntax

cpp
#include <iostream>

int main() {
    // Basic for loop syntax: for(initialization; condition; increment)
    std::cout << "=== Basic for loop ===" << std::endl;
    
    // Print numbers 1 to 5
    for (int i = 1; i <= 5; i++) {
        std::cout << "Number: " << i << std::endl;
    }
    
    // Reverse order
    for (int i = 5; i >= 1; i--) {
        std::cout << "Reverse: " << i << std::endl;
    }
    
    // Step size of 2
    for (int i = 0; i <= 10; i += 2) {
        std::cout << "Even number: " << i << std::endl;
    }
    
    return 0;
}

Range-based for Loop (C++11)

cpp
#include <iostream>
#include <vector>
#include <map>

int main() {
    // 1. Range-based for loop with arrays
    int numbers[] = {1, 2, 3, 4, 5};
    for (int num : numbers) {
        std::cout << "Number: " << num << std::endl;
    }
    
    // 2. Range-based for loop with vector
    std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
    for (const std::string& name : names) {
        std::cout << "Name: " << name << std::endl;
    }
    
    // 3. Modifying elements
    std::vector<int> values = {1, 2, 3, 4, 5};
    for (int& value : values) {
        value *= 2;  // Multiply each element by 2
    }
    
    // 4. Range-based for loop with map
    std::map<std::string, int> ages = {{"Alice", 25}, {"Bob", 30}};
    for (const auto& [name, age] : ages) {  // C++17 structured binding
        std::cout << name << "'s age: " << age << std::endl;
    }
    
    return 0;
}

Nested for Loops

cpp
#include <iostream>

int main() {
    // 1. Print multiplication table
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            std::cout << i << "×" << j << "=" << (i * j) << "\t";
        }
        std::cout << std::endl;
    }
    
    // 2. Print star triangle
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
            std::cout << "* ";
        }
        std::cout << std::endl;
    }
    
    return 0;
}

🔁 while Loop

Basic while Loop

cpp
#include <iostream>

int main() {
    // 1. Basic while loop
    int count = 1;
    while (count <= 5) {
        std::cout << "Count: " << count << std::endl;
        count++;
    }
    
    // 2. Loop controlled by user input
    char choice = 'y';
    int iteration = 0;
    
    while (choice == 'y' && iteration < 3) {
        iteration++;
        std::cout << "Iteration " << iteration << std::endl;
        // Simulate user input
        if (iteration >= 2) choice = 'n';
    }
    
    return 0;
}

while Loop Application Example

cpp
#include <iostream>

// Simple menu system
void showMenu() {
    std::cout << "\n=== Menu ===" << std::endl;
    std::cout << "1. Display information" << std::endl;
    std::cout << "2. Calculate square" << std::endl;
    std::cout << "0. Exit" << std::endl;
}

int main() {
    int choice = -1;
    
    while (choice != 0) {
        showMenu();
        
        // Simulate user input
        static int demo_choices[] = {1, 2, 0};
        static int demo_index = 0;
        choice = demo_choices[demo_index++];
        std::cout << "Choice: " << choice << std::endl;
        
        switch (choice) {
            case 1:
                std::cout << "Displaying system information..." << std::endl;
                break;
            case 2:
                std::cout << "Square of 5 is: " << (5 * 5) << std::endl;
                break;
            case 0:
                std::cout << "Exiting program..." << std::endl;
                break;
            default:
                std::cout << "Invalid choice!" << std::endl;
        }
    }
    
    return 0;
}

🔂 do-while Loop

Basic do-while Loop

cpp
#include <iostream>

int main() {
    // 1. Basic do-while loop
    int count = 1;
    do {
        std::cout << "Count: " << count << std::endl;
        count++;
    } while (count <= 5);
    
    // 2. Executes even when condition is false
    int never_true = 10;
    do {
        std::cout << "This will execute once, even if condition is false" << std::endl;
    } while (never_true < 5);
    
    // 3. Input validation example
    int user_input;
    int demo_inputs[] = {-1, 0, 5};  // Simulate user input
    int input_index = 0;
    
    do {
        user_input = demo_inputs[input_index++];
        std::cout << "Input number (1-10): " << user_input << std::endl;
        
        if (user_input < 1 || user_input > 10) {
            std::cout << "Invalid input, please try again!" << std::endl;
        }
    } while (user_input < 1 || user_input > 10);
    
    std::cout << "Valid input: " << user_input << std::endl;
    
    return 0;
}

🎮 Loop Control Statements

break and continue

cpp
#include <iostream>

int main() {
    // 1. break statement - exit loop
    std::cout << "=== break example ===" << std::endl;
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            std::cout << "Reached 5, breaking loop" << std::endl;
            break;
        }
        std::cout << "i = " << i << std::endl;
    }
    
    // 2. continue statement - skip current iteration
    std::cout << "\n=== continue example ===" << std::endl;
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        std::cout << "Odd number: " << i << std::endl;
    }
    
    // 3. Using break in nested loops
    std::cout << "\n=== break in nested loops ===" << std::endl;
    for (int i = 1; i <= 3; i++) {
        std::cout << "Outer i = " << i << std::endl;
        for (int j = 1; j <= 5; j++) {
            if (j == 3) {
                std::cout << "  Inner reached 3, breaking inner loop" << std::endl;
                break;  // Only breaks inner loop
            }
            std::cout << "  Inner j = " << j << std::endl;
        }
    }
    
    return 0;
}

🚀 Loop Best Practices

Performance and Readability Optimization

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
    
    // 1. Prefer range-based for loop (recommended)
    std::cout << "=== Range-based for loop (recommended) ===" << std::endl;
    for (const auto& name : names) {
        std::cout << name << std::endl;
    }
    
    // 2. Avoid recalculating size in loop condition
    std::cout << "\n=== Optimize loop condition ===" << std::endl;
    
    // Bad practice: calculating size() every time
    // for (int i = 0; i < names.size(); i++) { ... }
    
    // Good practice: cache size value
    const int size = names.size();
    for (int i = 0; i < size; i++) {
        std::cout << names[i] << std::endl;
    }
    
    // 3. Choose appropriate loop type
    std::cout << "\n=== Loop type selection guide ===" << std::endl;
    std::cout << "for loop: Known iteration count" << std::endl;
    std::cout << "while loop: Unknown iteration count, condition checked at start" << std::endl;
    std::cout << "do-while loop: Need to execute at least once" << std::endl;
    
    return 0;
}

Common Loop Patterns

cpp
#include <iostream>
#include <vector>

int main() {
    // 1. Traversal pattern
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    for (const int& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // 2. Accumulation pattern
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    std::cout << "Sum: " << sum << std::endl;
    
    // 3. Search pattern
    int target = 3;
    bool found = false;
    for (int num : numbers) {
        if (num == target) {
            found = true;
            break;
        }
    }
    std::cout << "Found " << target << ": " << (found ? "Yes" : "No") << std::endl;
    
    // 4. Filter pattern
    std::cout << "Even numbers: ";
    for (int num : numbers) {
        if (num % 2 == 0) {
            std::cout << num << " ";
        }
    }
    std::cout << std::endl;
    
    return 0;
}

📋 Loop Selection Guide

Loop Type Comparison

Loop TypeUse CaseAdvantagesNotes
for loopKnown iteration countClear structureAvoid repeated calculations in condition
Range-based forTraverse containersClean codeC++11 and later
while loopCondition-controlledFlexiblePrevent infinite loops
do-whileExecute at least onceGuaranteed executionEnsure loop terminates

Performance Considerations

cpp
// 1. Cache container size
const int size = container.size();
for (int i = 0; i < size; i++) { ... }

// 2. Use const reference to avoid copying
for (const auto& item : container) { ... }

// 3. Choose appropriate iteration method
for (auto it = container.begin(); it != container.end(); ++it) { ... }

Summary

C++ loop statements provide flexible and powerful repetition mechanisms:

Key Points

  • for loop: Suitable for iterations with known count, clear structure
  • Range-based for loop: Modern C++ recommended way to traverse containers
  • while loop: Suitable for condition-controlled loops
  • do-while loop: Scenarios requiring at least one execution

Best Practices

  • Prefer range-based for loops for container traversal
  • Reasonably use break and continue to control loop flow
  • Avoid expensive operations in loop conditions
  • Choose the most appropriate loop type for the scenario
  • Be careful to prevent infinite loops

Mastering loop statements is a fundamental programming skill. Correct use of loops can make code more concise and efficient.

Content is for learning and research only.