C++ Loops โ€” for, while, do-while & Range-Based for Masterclass

โšก Modern C++ (C++17 / C++20 / C++23) ๐ŸŸข Lesson 5 ๐Ÿ“‚ Phase 05: Loops & Control Flow ๐Ÿ“… 2026 Master Edition
๐Ÿ“Œ Covered in this in-depth guide: Standard for & while ยท Modern Range-Based for ยท break & continue ยท Star & Number Patterns ยท Vector Iteration ยท 9 Practice Programs

Welcome to Phase 5 (Chapter 5): C++ Loops โ€” for, while, do-while & Range-Based for Masterclass! Iteration structures execute code repeatedly. In Modern C++, range-based for (const auto &item : collection) provides safe, clean traversal of strings, vectors, and arrays.

1Loop Types Comparison Matrix
Loop ConstructSyntaxBest Use Case
Standard forfor (int i=0; i<n; i++)Known iteration count, index access needed
Range-Based forfor (const auto &x : vec)Modern traversal of containers without manual index counters
whilewhile (condition)Event-driven iteration where end condition is dynamic
do-whiledo { ... } while(cond);Guaranteed at least 1 execution (e.g. Menu loops)
29 Practice Programs Code Demonstration
C++ โ€” Prime, Fibonacci & Range-Based Loopโ–ถ Run Code in C++ Compiler
#include <iostream>
#include <vector>
#include <string>

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    // 1. Fibonacci Series Generation
    int n = 7, t1 = 0, t2 = 1, nextTerm;
    std::cout << "Fibonacci Series (7 terms): ";
    for (int i = 1; i <= n; ++i) {
        std::cout << t1 << " ";
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }
    std::cout << "\n";

    // 2. Prime Number Check
    int num = 29;
    std::cout << num << " is " << (isPrime(num) ? "PRIME" : "NOT PRIME") << "\n";

    // 3. Modern Range-Based For Loop Over Vector
    std::vector<std::string> fruits{"Apple", "Banana", "Cherry"};
    std::cout << "Fruits: ";
    for (const auto &fruit : fruits) {
        std::cout << fruit << " ";
    }
    std::cout << "\n";

    return 0;
}
3Technical FAQs

Q1: Why pass by const auto & in range-based for loops?

Passing by const auto & avoids making expensive copies of objects while guaranteeing the loop cannot modify elements.

Q2: What happens if you modify a vector inside a range-based for loop?

Adding/removing elements invalidates iterators, leading to Undefined Behavior crashes!

Q3: What is the difference between break and continue?

break exits the loop immediately. continue skips the rest of the current iteration and advances to the next loop step.

Q4: How do nested loops affect Big-O time complexity?

Two nested loops of size N yield O(Nยฒ) quadratic time complexity. Avoid deep nesting for large datasets.

Q5: Can do-while loops be infinite?

Yes, if the condition expression remains true continuously (e.g. `do { ... } while(true);`).