Topic 18 of 91 3. Control Flow in C++ Interactive Tutorial

Loops in C++: Repeating Instructions With Different Loop Constructs

15 mins read Last updated: 26 Sep 2026 22,500 views

Direct Answer & Core Concept

C++ offers four primary loop constructs: the classic for loop (ideal for counter-driven iterations), while loop (pre-condition loop executing 0 or more times), do-while loop (post-condition loop guaranteed to execute at least once), and the modern range-based for loop (C++11 for iterating across containers and arrays via begin()/end() iterators).

Detailed Explanation & Mechanics

1. Comparison of Loop Architectures:

Architecture Diagram
LOOP EVALUATION MODELS:
┌─────────────────┬───────────────────┬──────────────────────────────────────┐
│ Loop Type       │ Condition Check   │ Best Use Case                        │
├─────────────────┼───────────────────┼──────────────────────────────────────┤
│ for (init;c;inc)│ Pre-condition     │ Fixed number of iterations / index   │
│ while (cond)    │ Pre-condition     │ Event-driven / indeterminate cycles  │
│ do { } while(c);│ Post-condition    │ Prompting / executing at least once  │
│ for (auto& x: c)│ Range Iterator    │ Iterating over STL collections/arrays│
└─────────────────┴───────────────────┴──────────────────────────────────────┘

Runnable Code Example: Loops in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <vector>

int main() {
    // 1. Classic for loop
    std::cout << "For loop: ";
    for (int i = 1; i <= 3; ++i) {
        std::cout << i << " ";
    }
    std::cout << "
";

    // 2. while loop
    int count = 3;
    std::cout << "While loop: ";
    while (count > 0) {
        std::cout << count << " ";
        count--;
    }
    std::cout << "
";

    // 3. do-while loop (guaranteed at least one run)
    int value = 0;
    std::cout << "Do-While loop: ";
    do {
        std::cout << value << " ";
        value++;
    } while (value < 1);
    std::cout << "
";

    // 4. Range-based for loop (Modern C++)
    std::vector<std::string> nodes = {"alpha", "beta", "gamma"};
    std::cout << "Range-based for: ";
    for (const auto& node : nodes) {
        std::cout << "[" << node << "] ";
    }
    std::cout << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: How does a range-based for loop work under the hood?

A: The compiler expands `for (auto&& x : container)` into an equivalent traditional iterator loop calling `auto __begin = std::begin(container); auto __end = std::end(container); for (; __begin != __end; ++__begin)`.
Q

Q: Why should you use const auto& in range-based for loops?

A: Using `const auto&` binds elements by constant reference, preventing expensive object copying (e.g. copying `std::string` or `std::vector`) and guaranteeing read-only safety.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Default to range-based for loops for (const auto& item : container) when inspecting collections.
2. Use for (auto& item : container) when modifying elements in place.
3. Ensure loop termination conditions are reachable to prevent infinite execution.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.