</>
CompilerOnline
Open Interactive Editor

C++ Loops & Iterations

Loops in C++

Loops can execute a block of code as long as a specified condition is reached. C++ supports the traditional for, while, and do-while loops, alongside modern range-based iterations. They are vital for traversing collections and handling repetitive logic.

Traditional for loops use an initialization, condition check, and increment step. The while loop checks its condition before executing the body, whereas do-while guarantees at least one execution since it checks the condition at the end.

Range-Based For Loop

Introduced in C++11, this loop is specifically designed to iterate through all elements of a collection (like vectors, arrays, or lists) in a clean syntax. It eliminates indexing errors and improves readability.

Loop control statements like break and continue allow developers to alter loop paths. Optimizing loops by minimizing checks and caching array sizes is a key technique for maintaining high C++ execution speeds.

Iterating Over String Vectors

A range-based loop is particularly useful for traversing dynamically sized vectors containing strings, allowing you to access items without manual integer indexes.

cpp
#include <iostream>
#include <vector>
int main() {
    std::vector<std::string> items = {"C++", "Python", "JS"};
    for (const auto& item : items) {
        std::cout << "Lang: " << item << std::endl;
    }
    return 0;
}
cpp
#include <iostream>
#include <vector>

int main() {
    // Range-based for loop
    std::vector<int> nums = {10, 20, 30};
    for (int x : nums) {
        std::cout << "Value: " << x << std::endl;
    }
    return 0;
}