Ch6: Loops¶
TL;DR: Loop Paradigms:
for,while, anddo-whileloops control iteration.do-whileloops 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, anddo-whileloops control iteration.do-whileloops evaluate the test condition after executing the loop body, guaranteeing at least one run. - Standard Iterator Types:
size_tis 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
forloops 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.cpp11.Loops/11.3ForLoopMultipleDeclarations/main.cpp11.Loops/11.4CommaOperator/main.cpp11.Loops/11.5RangeBasedForLoop/main.cpp11.Loops/11.6WhileLoop/main.cpp11.Loops/11.7HugeLoopsWithOutput/main.cpp11.Loops/11.8DoWhileLoop/main.cpp11.Loops/11.9InfiniteLoops/main.cpp11.Loops/11.10InfiniteLoopPractice/main.cpp11.Loops/11.11DecrementingLoops/main.cpp11.Loops/11.12NestedLoops/main.cpp11.Loops/11.13BreakAndContinue/main.cpp11.Loops/11.14FixCalculator/main.cpp11.Loops/11.15ForLoopWithInitCondition/main.cpp