Programming with C++ – Iterative Statements
Iterative Statements
- Repetition constructs that run code blocks multiple times based on a condition.
- Provide concise, efficient handling of repetitive tasks.
Main Loop Categories
- for loop
- while loop
- do-while loop
- while(condition)statement
- dostatementwhile(condition);
- for(init;condition;update)statement
- Range-based: for(declaration:expression)statement
For Loop Highlights
- Order: initialization → condition test → body → update.
- Stops when the condition becomes false.
- Omitting all three fields for(;;) produces an intentional infinite loop.
While Loop Highlights
- Evaluates its condition before every iteration.
- Body executes only while the condition is true.
- Common infinite pattern: while(true)
Do-While Loop Highlights
- Executes body first, then tests the condition.
- Guarantees at least one pass through the loop body.
- Must terminate with a semicolon after while(⋯).
Controlling Loop Flow
- break: exits the nearest loop or switch immediately.
- continue: skips remaining body statements and proceeds to the next iteration.
- Other premature exits: return, goto, throw, exit().
Nested Loops
- One loop inside another; inner loop fully runs for each outer iteration.
- Typical pattern-printing example: nested i/j counters to output rows and columns.
Good Practice Reminders
- Ensure loop conditions eventually turn false to avoid endless execution.
- Combine loops with arrays and selection statements to build richer programs (e.g., Week Five task).