Control Flow: Loops
Repeat code with for, while, and do-while loops, and control iteration precisely with break, continue, and goto.
for Loop: Syntax and Structure
The for loop is the go-to choice when the number of iterations is known ahead of time. Its header packs initialization, condition, and update into one line.
for Loop
All three parts of the for header are optional, omitting the condition creates an infinite loop (for (;;)).
- Initialization: runs once before the first iteration (int i = 0)
- Condition: checked before each iteration; loop stops when false
- Update: runs at the end of each iteration (i++)
- The loop variable is scoped to the loop block when declared in the header
for Loop: Counting Up
C++Initialize i to 0, run while i is less than 5, increment after each pass.
Range-based for Loop (C++11)
The range-based for loop iterates over every element in a container or array without managing an index. It is cleaner and less error-prone than an index-based loop for simple traversal.
Range-based for
Use const auto& for the element type to avoid copying and prevent accidental modification.
- Syntax: for (type element : container) { }
- Works with arrays, vectors, strings, and any type with begin()/end()
- auto: lets the compiler deduce the element type
- auto&: reference, avoids copying; const auto&: read-only reference
Range-based for Loop
C++Iterate over a vector without managing an index variable.
Nested for Loops
A for loop placed inside another for loop is called a nested loop. For every single iteration of the outer loop, the inner loop runs to completion. They are commonly used for 2D grids and tables.
Nested for Loops
Total iterations = outer count multiplied by inner count, keep both counts small to avoid performance problems.
- Use different variable names for each level (i for outer, j for inner)
- A 3x3 grid needs 3 outer and 3 inner iterations = 9 total executions of the body
- break inside the inner loop only exits the inner loop, not the outer one
- Deep nesting (3+ levels) is hard to read, consider refactoring into a function
Nested for Loops: Multiplication Table
C++The inner loop completes all 4 columns before the outer loop moves to the next row.
while Loop: Syntax and Structure
The while loop checks its condition before each iteration. If the condition starts false, the body never runs. Use it when the number of iterations depends on runtime conditions rather than a fixed count.
while Loop
while is best when you don't know in advance how many iterations are needed, for example, reading input until the user types a sentinel value.
- Condition is evaluated before the body runs each time
- If the condition is false initially, the body runs zero times
- Make sure something inside the loop eventually makes the condition false, or it loops forever
- The loop variable must be declared and initialized before the while header
while Loop
C++Count from 1 to 5; the loop stops when n exceeds 5.
Infinite while Loop
Passing true as the condition creates a loop that runs forever. This is intentional in event-driven programs, servers, and game loops, you exit using break when a termination condition is met.
Infinite Loop
An infinite loop is only valid when you have a guaranteed break path inside the body, without one, the program hangs.
- while (true) { } is the conventional C++ infinite loop
- Always pair with a break or return statement for the exit condition
- Common in: game loops, server request handlers, menu-driven programs
- for (;;) { } is an equivalent and widely used alternative
Infinite while with break
C++The loop runs until the user enters 0, which triggers break.
do-while Loop: Syntax and Structure
The do-while loop places the condition check at the bottom, after the body. This guarantees the body runs at least once regardless of the condition.
do-while Loop
Use do-while when the action must happen before you can check whether to repeat, validating user input is the classic example.
- Syntax: do { body } while (condition);, note the semicolon after the closing parenthesis
- Body runs first, then the condition is evaluated
- If the condition is false on the first check, the body still ran once
- Less common than for and while; use it only when the at-least-once guarantee is needed
do-while: Input Validation
C++Prompt at least once, then keep prompting until the correct PIN is entered.
Difference Between while and do-while
The only structural difference is when the condition is checked: before the body (while) or after it (do-while). This changes the minimum number of times the body can execute.
while vs do-while
If the condition could be false from the very start, while may run zero times while do-while will always run at least once.
- while: condition checked first, body may run 0 or more times
- do-while: body runs first, body runs 1 or more times
- Both are equivalent when the condition starts true
- Prefer while; only reach for do-while when the at-least-once semantic is genuinely needed
| Feature | while | do-while |
|---|---|---|
| Condition checked | Before the body | After the body |
| Minimum executions | 0 (may never run) | 1 (always runs once) |
| Semicolon after condition | No | Yes, do { } while (cond); |
| Typical use case | General repetition | Input validation, menus |
break Statement
break immediately exits the innermost loop (or switch) it appears in. Execution resumes at the first statement after the closing brace of that loop.
break
break only exits one level, if you are inside nested loops and need to break out of all of them, you need a flag variable or goto (use the flag).
- Exits the innermost enclosing for, while, do-while, or switch
- Useful for searching: break as soon as you find what you need
- To exit multiple nested loops, set a bool flag and check it in each loop
- Overusing break makes loop logic hard to follow, consider restructuring
break: Early Exit
C++Stop the loop as soon as the first even number is found.
continue Statement
continue skips the rest of the current iteration and jumps to the next one. Unlike break, it does not exit the loop, it just moves on to the next pass.
continue
continue is useful for filtering, skip unwanted values and process only the ones you care about.
- In a for loop, continue jumps to the update expression (i++), then re-checks the condition
- In a while loop, continue jumps back to the condition check
- Only affects the innermost loop, just like break
- Too many continues in one loop can obscure the main logic, consider an if-else instead
continue: Skip Even Numbers
C++continue jumps back to i++ whenever i is even, so only odd numbers are printed.
goto Statement (and Why to Avoid It)
goto transfers execution unconditionally to a labeled statement anywhere in the same function. It is legal C++ but considered harmful because it creates unstructured, hard-to-follow control flow.
goto
Every legitimate use of goto can be replaced with break, continue, a flag variable, or a refactored function, always prefer those.
- Syntax: goto labelName; ... labelName: (statement);
- Can jump forward or backward within the same function
- Creates spaghetti code: makes it impossible to reason about program state
- Skipping variable initializations with goto is undefined behavior
- The only debated exception: breaking out of deeply nested loops, use a flag instead
goto (Avoid This)
C++This does the same as a for loop but is far harder to read. Use a loop instead.
Loop Types at a Glance
| Loop | Condition Checked | Min Iterations | Best For |
|---|---|---|---|
| for | Before body | 0 | Known iteration count |
| Range-based for | Before body | 0 | Iterating containers |
| while | Before body | 0 | Unknown count, condition-driven |
| do-while | After body | 1 | At-least-once (input validation) |
Knowledge Check
1. In a for loop written as for (int i = 0; i < 5; i++), how many times does the body execute?
2. What is the key difference between while and do-while?
3. What does the continue statement do inside a loop?
4. Which loop type is best when the number of iterations is known in advance?
5. What does the range-based for loop require the container to support?
6. Why should goto be avoided?