Unit 2: Loops, Functions & ScopeLesson #5 / 20

Lesson 5: Iteration Mastery: for, while, do-while & Range-Based Loops

NSNextSem•Last Updated: 5 Aug, 2026

šŸ” Loop Constructs in C++

Loops execute a block of code repeatedly as long as a specified condition remains true. Modern C++ (C++11 and higher) also introduces range-based for loops for effortless container traversal.


šŸ”„ Loop Types Comparison

  • šŸŽÆ for (init; condition; update): Used when the exact number of iterations is known beforehand.
  • ā³ while (condition): Evaluates condition before executing the loop body.
  • šŸ” do { ... } while (condition);: Executes body first, then checks condition (guarantees at least 1 run).
  • ⚔ for (const auto& item : collection): Clean C++11 range-based loop for arrays and STL vectors.

  • šŸ’» Code Example: Iteration & Range Traversal

    āŠžC++ Source Code (main.cpp)
    #include <iostream>
    #include <vector>
    int main() {
    // 1. Traditional for loop
    std::cout << "--- Counting 1 to 5 ---" << std::endl;
    for (int i = 1; i <= 5; ++i) {
    std::cout << "Count: " << i << std::endl;
    }
    // 2. Range-based for loop (C++11)
    std::vector<std::string> frameworks = {"Qt", "Unreal Engine", "Boost", "CUDA"};
    std::cout << "
    --- C++ High Performance Frameworks ---" << std::endl;
    for (const auto& fw : frameworks) {
    std::cout << "⚔ " << fw << std::endl;
    }
    return 0;
    }
    āŠžWindows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    āŠžAdministrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
    ā€”ā–”āœ•

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    šŸ› ļø Execution Output on āŠž Windows 11 CMD:

    āŠžCommand Execution Snippet
    --- Counting 1 to 5 ---
    Count: 1
    Count: 2
    Count: 3
    Count: 4
    Count: 5
    --- C++ High Performance Frameworks ---
    ⚔ Qt
    ⚔ Unreal Engine
    ⚔ Boost
    ⚔ CUDA
    āŠžWindows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    āŠžAdministrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
    ā€”ā–”āœ•

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>--- Counting 1 to 5 ---

    C:\Users\Student\CPP_Project> --- Counting 1 to 5 --- Execution successful! Output verified on Windows 11 Pro x86_64. [Process exited with code 0 in 0.002 seconds]

    Interactive Knowledge Check

    Test your understanding of Lesson #5 concepts

    Which C++ loop guarantees that the body of the loop will execute AT LEAST ONCE?