[2026] C++ Loops Masterclass: for, while, do-while, Range-for, and Escaping Nested Loops
이 글의 핵심
Choose the right loop: counted for, condition-driven while, do-while for at-least-once, range-based for, break/continue rules, off-by-one, and floating-point loop pitfalls.
Basic for loop
for (int i = 1; i <= 10; i++) {
std::cout << i << " ";
}
for structure
아래 코드는 cpp를 사용한 구현 예제입니다. 반복문으로 데이터를 처리합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
for (init; condition; increment) {
// body
}
for (int i = 0; i < 5; i++) {
std::cout << i << std::endl;
}
while loop
아래 코드는 cpp를 사용한 구현 예제입니다. 반복문으로 데이터를 처리합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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
| Form | Good when |
|---|---|
| for | Known iteration count; init/condition/increment on one line; index 0..n-1 |
| while | Condition-driven: input, EOF, flags |
| do-while | Must 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
breakexits the innermost enclosing loop orswitchonly.continueskips 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
다음은 간단한 cpp 코드 예제입니다. 반복문으로 데이터를 처리합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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.
Related posts (internal links)
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?