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\textbf{for} loop
  • while\textbf{while} loop
  • do-while\textbf{do\text{-}while} loop

Core Syntax (C++ Standard Forms)

  • while(condition)  statement\textbf{while}(\text{condition})\;\text{statement}
  • do  statement  while(condition);\textbf{do}\;\text{statement}\;\textbf{while}(\text{condition});
  • for(init;  condition;  update)  statement\textbf{for}(\text{init};\;\text{condition};\;\text{update})\;\text{statement}
  • Range-based: for(declaration:expression)  statement\textbf{for}(\text{declaration} : \text{expression})\;\text{statement}

For Loop Highlights

  • Order: initialization → condition test → body → update.
  • Stops when the condition becomes false.
  • Omitting all three fields for(;;)\textbf{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)\textbf{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()\textbf{while}(\cdots).

Controlling Loop Flow

  • break\textbf{break}: exits the nearest loop or switch immediately.
  • continue\textbf{continue}: skips remaining body statements and proceeds to the next iteration.
  • Other premature exits: return\textbf{return}, goto\textbf{goto}, throw\textbf{throw}, exit()\text{exit()}.

Nested Loops

  • One loop inside another; inner loop fully runs for each outer iteration.
  • Typical pattern-printing example: nested ii/jj 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).