Skip to content

Ch6: Loops

TL;DR: Loop Paradigms: for, while, and do-while loops control iteration. do-while loops evaluate the test condition after executing the loop body, guaranteeing at least one run.

โšก Quick Reference

#include <iostream>

int main() {
    // for (init; condition; increment) - Standard entry-controlled loop.
    for (int i = 0; i < 5; ++i) {
        // continue - Skips remaining statements in the current iteration.
        if (i == 2) continue;
        // break - Immediately terminates loop execution.
        if (i == 4) break;
        std::cout << i << " ";
    }
    std::cout << std::endl;

    // while (condition) - Pre-tested loop that executes while condition remains true.
    int count = 0;
    while (count < 3) {
        std::cout << count << " ";
        ++count;
    }
    std::cout << std::endl;

    // do { ... } while (condition); - Post-tested loop executing at least once.
    int k = 0;
    do {
        std::cout << k << " ";
        ++k;
    } while (k < 3);
    std::cout << std::endl;

    return 0;
}

๐Ÿง  Core Concepts

  • Loop Paradigms: for, while, and do-while loops control iteration. do-while loops evaluate the test condition after executing the loop body, guaranteeing at least one run.
  • Standard Iterator Types: size_t is the standard unsigned integer type for collection sizes. On 64-bit systems, it is 8 bytes. It underflows if decremented below zero.
  • Range-Based Iteration: Range-based for loops iterate directly over collections or initializer lists without manual indexing, but do not support reverse iteration natively.

โš ๏ธ Pitfalls (Quick Scan)

Mistake Fix
Accessing loop iterator outside loop scope Declare iterator before loop statement if its final value is needed
Hardcoding loop bounds Define loop boundaries using const size_t constants
Forgetting iterator incrementation in while loops Ensure loop body contains iterator updates
Assuming do-while loops can check condition on first run Use standard for or while loop if zero-run path is required
Decrementing unsigned size_t below zero Avoid decrementing unsigned counters past zero, e.g., i > 0 condition (11.11)
Using unsigned comparison i >= 0 for decrements Change type to signed integer or use i > 0 and adjust indexes (11.11)
Relying on range-based for loop for reverse iteration Use manual index loop or std::reverse_iterator (11.11)
Forgetting to reset inner counter in nested loops Reset inner loop iterator to zero after outer loop begins (11.12)
Calling continue without incrementing iterator in while loop Perform increment operation immediately before calling continue (11.13)
Misunderstanding comma operator assignment Use parenthesized comma lists or separate statements for clarity (11.4)

๐Ÿ“– Full Details

Cause โ†’ Effect โ†’ Fix with timestamp (click to expand) * **Accessing loop iterator outside loop scope** -> **Compile-time error because iterator is destroyed after loop exits** -> **Declare iterator before loop statement if its final value is needed (12:20)** * **Hardcoding loop bounds** -> **Difficult maintenance when array bounds change** -> **Define loop boundaries using `const size_t` constants (15:48)** * **Forgetting iterator incrementation in `while` loops** -> **Infinite loop execution and program hang** -> **Ensure loop body contains iterator updates (13:00)** * **Assuming `do-while` loops can check condition on first run** -> **Loop body executes at least once regardless of initial condition** -> **Use standard `for` or `while` loop if zero-run path is required (18:00)** * **Decrementing unsigned `size_t` below zero** -> **Value wraps around (underflows) to maximum positive integer limit** -> **Avoid decrementing unsigned counters past zero, e.g., `i > 0` condition (11.11)** * **Using unsigned comparison `i >= 0` for decrements** -> **Infinite loop because unsigned variable is always non-negative** -> **Change type to signed integer or use `i > 0` and adjust indexes (11.11)** * **Relying on range-based `for` loop for reverse iteration** -> **No native compiler syntax for reverse traversal** -> **Use manual index loop or `std::reverse_iterator` (11.11)** * **Forgetting to reset inner counter in nested loops** -> **Subsequent outer loop iterations skip the inner loop** -> **Reset inner loop iterator to zero after outer loop begins (11.12)** * **Calling `continue` without incrementing iterator in `while` loop** -> **Increment step is skipped, causing an infinite loop** -> **Perform increment operation immediately before calling `continue` (11.13)** * **Misunderstanding comma operator assignment** -> **Variable is assigned rightmost operand only instead of a tuple** -> **Use parenthesized comma lists or separate statements for clarity (11.4)**

๐Ÿ“Ž Repo Files

  • 11.Loops/11.2ForLoop/main.cpp
  • 11.Loops/11.3ForLoopMultipleDeclarations/main.cpp
  • 11.Loops/11.4CommaOperator/main.cpp
  • 11.Loops/11.5RangeBasedForLoop/main.cpp
  • 11.Loops/11.6WhileLoop/main.cpp
  • 11.Loops/11.7HugeLoopsWithOutput/main.cpp
  • 11.Loops/11.8DoWhileLoop/main.cpp
  • 11.Loops/11.9InfiniteLoops/main.cpp
  • 11.Loops/11.10InfiniteLoopPractice/main.cpp
  • 11.Loops/11.11DecrementingLoops/main.cpp
  • 11.Loops/11.12NestedLoops/main.cpp
  • 11.Loops/11.13BreakAndContinue/main.cpp
  • 11.Loops/11.14FixCalculator/main.cpp
  • 11.Loops/11.15ForLoopWithInitCondition/main.cpp