Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 3 of 8

Loops - for, while, do-while & Range-based for

C++ has three classic loop forms plus the **range-based for** (C++11) which works with any type that provides `begin()`/`end()`. Range-based for is the preferred loop for iterating containers - it's more readable, less error-prone (no off-by-one), and compiles to the same assembly as the index-based version.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

All Loop Forms - With Perf-Conscious Patterns

All Loop Forms - With Perf-Conscious Patterns
#include <iostream>
#include <vector>
#include <string>

int main() {
    // ── Classic for ───────────────────────────────────────────
    for (int i = 0; i < 5; ++i) {         // prefer ++i (no copy for iterators)
        std::cout << i << " ";
    }
    std::cout << "
";  // 0 1 2 3 4

    // Multiple variables
    for (int i = 0, j = 10; i < j; ++i, --j) {
        std::cout << "(" << i << "," << j << ") ";
    }
    std::cout << "
";

    // ── while ─────────────────────────────────────────────────
    int n = 256;
    int count = 0;
    while (n > 1) { n /= 2; ++count; }
    std::cout << "log2(256) = " << count << "
";  // 8

    // ── do-while - executes at least once ─────────────────────
    int attempts = 0;
    do {
        ++attempts;
        std::cout << "Attempt " << attempts << "
";
    } while (attempts < 3);

    // ── Range-based for (C++11) ──────────────────────────────
    std::vector<int> nums{10, 20, 30, 40, 50};

    // Read-only: const auto& - no copy, no mutation
    for (const auto& n : nums) {
        std::cout << n << " ";
    }
    std::cout << "
";

    // Modify: auto& - mutates elements
    for (auto& val : nums) { val *= 2; }

    // Copy (when you actually need a copy per iteration)
    for (auto copy : nums) { copy += 1; }  // nums unchanged

    // With index - if you need both index and value
    for (std::size_t i = 0; i < nums.size(); ++i) {
        std::cout << "[" << i << "]=" << nums[i] << " ";
    }
    std::cout << "
";

    // ── break & continue ─────────────────────────────────────
    for (int i = 0; i < 10; ++i) {
        if (i == 3) continue;   // skip 3
        if (i == 7) break;      // stop at 7
        std::cout << i << " ";
    }
    std::cout << "
";  // 0 1 2 4 5 6

    // ── Iterating strings ─────────────────────────────────────
    std::string word = "Hello";
    for (char c : word) {
        std::cout << static_cast<int>(c) << " ";  // ASCII values
    }
    std::cout << "
";

    // ── Iterating C-arrays ────────────────────────────────────
    int arr[] = {1, 2, 3, 4, 5};
    for (const auto& elem : arr) { std::cout << elem << " "; }
    std::cout << "
";

    return 0;
}

Common Mistakes

  • `for (auto elem : vec)` copies each element - for a `vector<std::string>`, this copies every string on each iteration. Always use `const auto&` for read-only iteration.
  • Comparing signed and unsigned - `for (int i = 0; i < vec.size(); ++i)` - `vec.size()` returns `size_t` (unsigned). If `vec.size() == 0`, `i < vec.size()` compares `int` with `size_t`, which can be surprising. Use `for (std::size_t i = 0; ...)` or range-based for.
  • Modifying container size during range-based for - adding or removing elements from a `vector` during range-based for iteration invalidates iterators, causing undefined behaviour. Collect indices to remove and erase after the loop.

Tip

Tip

Practice Loops for while dowhile Rangebased for in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Pre-test vs Post-test loops, loop control statements, and modern C++11 range-based for

Practice Task

Note

Practice Task - (1) Write a working example of Loops for while dowhile Rangebased for from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Loops for while dowhile Rangebased for is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • C++ has three classic loop forms plus the **range-based for** (C++11) which works with any type that provides `begin()`/`end()`.
  • `for (auto elem : vec)` copies each element - for a `vector<std::string>`, this copies every string on each iteration. Always use `const auto&` for read-only iteration.
  • Comparing signed and unsigned - `for (int i = 0; i < vec.size(); ++i)` - `vec.size()` returns `size_t` (unsigned). If `vec.size() == 0`, `i < vec.size()` compares `int` with `size_t`, which can be surprising. Use `for (std::size_t i = 0; ...)` or range-based for.
  • Modifying container size during range-based for - adding or removing elements from a `vector` during range-based for iteration invalidates iterators, causing undefined behaviour. Collect indices to remove and erase after the loop.

Topics in This Module

0/8 done