C++ Loops Masterclass: for, while, do-while, Range-for, and Escaping Nested Loops

C++ Loops Masterclass: for, while, do-while, Range-for, and Escaping Nested Loops

이 글의 핵심

Practical guide to for/while/do-while, range-based for, infinite loops with break, nested loops, and performance habits—without premature micro-optimization.

Basic for loop

for (int i = 1; i <= 10; i++) {
    std::cout << i << " ";
}

for structure

for (init; condition; increment) {
    // body
}

for (int i = 0; i < 5; i++) {
    std::cout << i << std::endl;
}

while loop

int i = 1;
while (i <= 10) {
    std::cout << i << " ";
    i++;
}

do-while

Runs at least once—condition checked after the body.

Choosing: for vs while vs do-while

FormGood when
forKnown iteration count; init/condition/increment on one line; index 0..n-1
whileCondition-driven: input, EOF, flags
do-whileMust execute body once (menus, validate-then-check)

Range-based for (C++11)

Prefer for (const auto& x : vec) for readability when you do not need the index.

break and continue

  • break exits the innermost enclosing loop or switch only.
  • continue skips to the next iteration of the innermost loop.

Infinite loops

while (true) / for (;;) with break/return on valid exit paths—avoid continue loops that never advance state.

Nested loops

Multiplication table, patterns, primes—watch complexity: O(n²) vs better algorithms matters more than tiny loop tweaks.

Exiting nested loops

Use flags, refactor into functions that return, or in rare cases goto with team approval.

Common mistakes

Infinite loop (missing update)

Ensure the condition can become false.

Off-by-one

Be explicit: i < n vs i <= n.

Stray semicolon

for (int i = 0; i < 10; i++);  // empty loop body
{
    std::cout << "runs once\n";
}

Examples (from original)

Prime printing, input validation loop, Fibonacci generation—same algorithms as the Korean article.

Vector iteration pitfalls

Do not grow a vector while iterating up to v.size() without caching the initial size or using a different strategy.

Floating-point loop counter

Avoid for (double x = 0; x != 1.0; x += 0.1). Prefer integer counters and derive double x = i * 0.1.

Performance notes

Hoist invariant computations out of loops; use const T& in range-for for large objects; profile before micro-optimizing.


  • if/switch
  • Range-based for
  • std::string

Practical tips

Debugging

  • Warnings; reproduce with small inputs.

Performance

  • Profile; fix algorithm class first.

Code review

  • Conventions for loop style.

Practical checklist

Before coding

  • Simplest loop form for readers?

While coding

  • All paths terminate?

During review

  • Nested depth acceptable?

C++, for, while, loops, control flow