Programming Lecture 03: Flow of Control and Repetition Structures in C++
Flow of Execution and Fundamentals of Repetition
- Categories of Flow of Execution:
- Sequential: Execution proceeds line-by-line in sequential order ().
- Selection: Execution branches based on the truth value of a condition (), executing either a
truebranch () or afalsebranch (). - Repetition: Also called looping, execution repeats a statement block () continuously as long as an entry condition () evaluates to
true.

Purpose and Necessity of Repetition:
- Allows efficient utilization of variables in program design.
- Enables receiving input, performing calculations, and aggregating operations over multiple data entries using a fixed, minimal set of variables.
- Summation Example (Adding 5 numbers):
- Without repetition: Requires declaring 5 distinct variables (e.g.,
num1,num2,num3,num4,num5), prompting individual inputs for each, and manually adding all variables together (sum = num1 + num2 + num3 + num4 + num5). - With repetition: Utilizes a loop construct to read a single number into a reusable variable during each iteration, accumulating the value directly into a single sum variable (
sum += num).
Three Repetition Constructs in C++:
while: Pre-test loop structure. Offers maximum flexibility with no structural restrictions.do...while: Post-test loop structure. Least flexible, but guarantees that the loop body executes at least once.for: Pre-test loop structure. Formatted specifically for counter-controlled or natural counting operations.
The while Loop
- Syntax and Formal Specification:
while (entry_cond)
statement_while;
```
- `entry_cond`: A decision-making expression, typically evaluating to a boolean value (`true` or `false`). The enclosing parentheses `()` are mandatory syntax.
- `statement_while`: Represents the body of the loop. Can be either a simple statement ending with a semicolon or a compound statement enclosed within curly braces `{}`.
- **Operational Semantics**:
- `entry_cond` is evaluated first upon loop entry.
- If `entry_cond` evaluates to `true`, `statement_while` executes.
- Upon completion of `statement_while`, control loops back and re-evaluates `entry_cond`.
- Execution continues repeatedly until `entry_cond` evaluates to `false`, at which point control transfers to the statement immediately following the loop construct.

- **Execution Trace Examples**:
- **Example 1 (True Condition Path)**:
```cpp
num = 0; // Initialization
while (num < 10) // Loop Condition
{
cout << 2 * num << " "; // Loop Body
num += 2; // Update Expression
}
cout << endl;
```
- *Iteration Trace*:
- `num = 0`: `0 < 10` is `true` outputs `0`, updates `num` to `2`.
- `num = 2`: `2 < 10` is `true` outputs `4`, updates `num` to `4`.
- `num = 4`: `4 < 10` is `true` outputs `8`, updates `num` to `6`.
- `num = 6`: `6 < 10` is `true` outputs `12`, updates `num` to `8`.
- `num = 8`: `8 < 10` is `true` outputs `16`, updates `num` to `10`.
- `num = 10`: `10 < 10` is `false` exits loop.
- *Sample Run Output*: `0 4 8 12 16`
- **Example 2 (Initially False Condition Path)**:
```cpp
num = 30;
while (num < 24) // Condition never satisfied (30 < 24 is false)
{
cout << num << " ";
num += 5;
}
cout << endl;
```
- *Iteration Trace*: `30 < 24` evaluates to `false` immediately on initial evaluation. The loop body executes 0 times.
- *Sample Run Output*: (blank line)
# Four Categories of while Loop Control Structures
- **1. Counter-Controlled Loop**:
- Used when the exact number of data items or iterations is known prior to loop execution.
- Involves initializing a counter variable, evaluating it against a limit threshold, and updating the counter inside the loop body.
- *Structure Template*:
```cpp
num = 0; // Initialize loop control
while (num < LIMIT) // Test loop control
{
// statements...
num++; // Update loop control
}
```
- **2. Sentinel-Controlled Loop**:
- Used when the exact number of iterations is unknown, but a designated input value (the *sentinel*) signals loop termination.
- Requires reading an initial input value prior to loop entry (priming read), checking whether it matches the sentinel value, and reading subsequent inputs at the bottom of the loop body.
- *Structure Template*:
```cpp
cin >> tok; // Initialize control token (priming read)
while (tok != 'Y') // 'Y' is the sentinel value
{
// statements...
cin >> tok; // Update control token
}
```
- **3. Flag-Controlled Loop**:
- Uses a boolean variable (a *flag*) to monitor status changes and control loop execution.
- *Structure Template*:
```cpp
int a = 2; // Initialize loop variable
bool flag = false; // Initialize loop control flag
while (!flag) // Test loop control flag
{
if (a < 100) // Update condition check
{
a *= 2;
flag = true; // Update loop control flag
}
}
```
- **4. EOF-Controlled (End-of-File) Loop**:
- Operates continuously until the input stream encounters an End-of-File (EOF) signal generated by an input device or file.
- *Operating System Keyboard EOF Signals*:
- `Ctrl+z` on Windows operating systems.
- `Ctrl+d` on Linux / Unix operating systems.
- *The `eof()` Member Function*:
- `eof()` is a member function of the `istream` class (included via header `<iostream>`).
- *Syntax*: `istreamObj.eof()`, e.g., `cin.eof()`.
- Returns `true` if an end-of-file condition has been detected on the stream; otherwise `false`.
- *Stream Clearing*: `cin.clear();` resets stream status state bits, allowing the program to restart reading from input devices.
- *Form 1 (Direct Input Extraction Evaluation)*:
```cpp
char xx;
while (cin >> xx) // Test stream read directly
{
cout << xx;
}
cin.clear(); // Reset stream state
```
- *Form 2 (Explicit `!cin.eof()` Check)*:
```cpp
char yy;
cin >> yy;
while (!cin.eof()) // Explicit eof status check
{
cout << yy;
cin >> yy;
}
cin.clear(); // Reset stream state
```
# Common Pitfalls of while Loops
- **Misplaced Semicolon (`;`)**:
- Placing a semicolon immediately after the `while (condition)` clause treats the empty statement `;` as the entire loop body.
- *Code Example*:
```cpp
while (xx != 0); // Misplaced semicolon creates a null statement loop body!
{
cout << "Enter value: ";
cin >> xx;
}
```
- *Impact*: If `xx != 0` evaluates to `true`, the program enters an infinite loop executing the empty semicolon statement endlessly, never executing the statement block inside `{}`.
- **Infinite Loops**:
- Occurs whenever the loop condition never evaluates to `false` across iterations.
- *Syntactically Valid Infinite Loop Structure*:
```cpp
while (1)
{
cout << "... ";
}
```
- *Causes*: Omitting variable update statements inside the loop body or setting updates that move the variable away from the termination condition.
- *Practical Application*: Intentional infinite loops are used in specialized applications such as embedded systems.
# The for Loop
- **Syntax and Structural Mechanics**:
cpp for (init_stmt; lp_cond; update_stmt) statement_for; ```
init_stmt: Initialization statement. Executed once prior to entering the loop to set control variables.lp_cond: Loop condition expression. Evaluated before each iteration; iftrue, the body executes; iffalse, the loop terminates.update_stmt: Update statement. Executed at the end of each iteration to modify control variables.statement_for: Loop body statement (simple or compound{}).

Structural Equivalence between for and while Loops:
- Converting
fortowhile:
init_stmt; while (lp_cond) { stmt_for; update_stmt; } ``` - Converting `while` to `for`:cpp for ( ; entry_cond; ) { stmt_while; } ```
- Converting
Omission of Header Elements:
- All three components (
init_stmt,lp_cond,update_stmt) are optional, but both internal semicolons;are strictly required by syntax. - Omitting
lp_conddefaults the condition evaluation totrue. - Infinite loop form:
for ( ; ; ) { stmt_for; }.
- All three components (
Code Comparison and Structural Examples:
- Standard Count-Controlled for Loop:
for (int idx = 2; idx <= 20; idx += 2) { cout << idx << " "; } ``` - *Output*: `2 4 6 8 10 12 14 16 18 20` - *Modified Variant 1a (External Initialization)*:cpp int idx = 2; for ( ; idx <= 20; idx += 2) { cout << idx << " "; } ```
- Modified Variant 1b (In-Body Update):
int idx = 2; for ( ; idx <= 20; ) { cout << idx << " "; idx += 2; } ``` - *Modified Variant 1c (Equivalent while Structure)*:cpp int idx = 2; while (idx <= 20) { cout << idx << " "; idx += 2; } ```
Compound vs. Single Statement Scope Examples:
- Properly Enclosed Compound Body:
for (int idx = 1; idx <= 3; idx++) { cout << "Okay"; cout << "!" << endl; } ``` - *Output*:text Okay! Okay! Okay! ```
- Omitted Braces Scenario (Example 2a):
for (idx = 1; idx <= 3; idx++) cout << "Okay"; cout << "*" << endl; ``` - *Output*: `OkayOkayOkay*` (Only `cout << "Okay";` is inside the loop scope; `cout << "*"` runs once after loop termination). - *Misplaced Semicolon Scenario (Example 2b)*:cpp for (int idx = 1; idx <= 3; idx++) ; cout << "Okay"; cout << "!" << endl; ```
- Output:
Okay!(The misplaced semicolon creates an empty body; the loop iterates 3 times doing nothing, after which the remaining lines run once).
Rules and Floating-Point Control Variable Caveat:
- If
lp_condis initiallyfalse, the loop body executes 0 times (e.g.,for (int idx = 0; idx > 0; idx++) {;}). update_stmtmust move the variable state toward terminatinglp_cond(e.g.,for (idx = 0; idx < 10; idx--) {;}creates an infinite loop).- Floating-Point Variable Warning: Avoid using
floatordoubledata types as loop control variables (e.g.,for (double idx = 0.1; idx < 0.75; idx += 0.05)). Floating-point representation limits and rounding inaccuracies yield inconsistent results across different hardware architectures.
- If
The do…while Loop
- Syntax and Structural Mechanics:
do
stmt_dowhile;
while (rep_cond);
```
- *Note*: The terminating semicolon `;` following `while (rep_cond)` is required by syntax.
- **Operational Characteristics**:
- Post-test loop structure: `stmt_dowhile` executes **first**, after which `rep_cond` is evaluated.
- If `rep_cond` evaluates to `true`, control returns to re-execute `stmt_dowhile`.
- If `rep_cond` evaluates to `false`, the loop terminates.
- **Guaranteed Execution**: Always executes the loop body at least once regardless of the initial truth value of `rep_cond`.

- **Execution Examples**:
- **Example 1**:
```cpp
idx = 1;
do
{
cout << idx << " ";
idx += 3;
} while (idx <= 20);
```
- *Iteration Trace*:
- Executes body: prints `1`, updates `idx` to `4`. Check: `4 <= 20` is `true`.
- Executes body: prints `4`, updates `idx` to `7`. Check: `7 <= 20` is `true`.
- Executes body: prints `7`, updates `idx` to `10`. Check: `10 <= 20` is `true`.
- Executes body: prints `10`, updates `idx` to `13`. Check: `13 <= 20` is `true`.
- Executes body: prints `13`, updates `idx` to `16`. Check: `16 <= 20` is `true`.
- Executes body: prints `16`, updates `idx` to `19`. Check: `19 <= 20` is `true`.
- Executes body: prints `19`, updates `idx` to `22`. Check: `22 <= 20` is `false` exits loop.
- *Screen Output*: `1 4 7 10 13 16 19`
- **Example 2: Comparison under Initially False Condition**:
- *`do...while` Implementation (Example 2a)*:
```cpp
num = 13;
do
{
num %= 7;
} while (num > 13);
cout << num;
```
- Body executes once: `num` becomes `13 % 7 = 6`. Check: `6 > 13` evaluates to `false`. Exits loop.
- *Screen Output*: `6`
- *`while` Implementation (Example 2b)*:
```cpp
num = 13;
while (num > 13)
{
num %= 7;
}
cout << num;
```
- Check: `13 > 13` evaluates to `false` immediately. Body executes 0 times.
- *Screen Output*: `13`
# Loop Control Alterations: break and continue
- **General Flow Principles**:
- Repetition constructs provide structured entry and exit points.
- `break` and `continue` alter natural execution flow and should be used only when necessary.
- **The break Statement**:
- Forces immediate exit from looping structures (`while`, `for`, `do...while`) or `switch` statements.
- Execution jumps directly to the statement following the loop structure.
- *Example*:
```cpp
for (num = 10; num <= 40; num += 2)
{
if (num % 8 == 0)
break;
cout << num << " ";
}
```
- *Trace*: `num = 10` (outputs `10`), `num = 12` (outputs `12`), `num = 14` (outputs `14`), `num = 16` (`16 % 8 == 0` is `true` triggers `break`).
- *Screen Output*: `10 12 14`
- **The continue Statement**:
- Skips the remaining statements in the loop body for the current iteration and begins the next iteration immediately.
- Transfers execution to the top condition evaluation in `while` and `do...while` loops, or to `update_stmt` in `for` loops.
- Applies exclusively to repetition structures (`while`, `for`, `do...while`).
- *Example*:
```cpp
num = 0;
while (num < 20)
{
num += 2;
if (num == 10)
continue;
cout << num << " ";
}
```
- *Trace*: `num` increments by 2 each pass (`2, 4, 6, 8` outputted). When `num == 10`, `continue` skips `cout` and jumps to `num < 20`. `num` becomes `12, 14, 16, 18, 20` (outputted).
- *Screen Output*: `2 4 6 8 12 14 16 18 20`
# Nested Control Structures
- **Definition**: A nested loop structure consists of a loop defined entirely inside another loop.
- **Operational Rules**:
- For **each single iteration** of the outer loop, the inner loop executes its entire complete cycle from start to finish.
- Distinct control variables **must** be used for outer and inner loops (e.g., `idx` for outer, `jdx` for inner).
- The inner loop construct must be contained completely within the outer loop body boundaries.
- **Example 1: 9x9 Multiplication Tables**:
cpp for (int idx = 1; idx <= 9; idx++) // Outer loop { cout << idx << "-multiples: " << endl; for (int jdx = 1; jdx <= 9; jdx++) // Inner loop { cout << idx * jdx << " "; } // End of inner loop cout << endl; } // End of outer loop ```
- Example 2: Printing a 5-Level Triangle Pattern:
cpp cout << "Enter char: "; char c; cin >> c; for (int i = 0; i < 5; i++) { for (int j = 0; j < (4 - i); j++) { cout << " "; } for (int j = 0; j < (2 * i + 1); j++) { cout << c; } cout << endl; } - Output Pattern Analysis for Input character
'w': i = 0: prints4spaces,1'w'wi = 1: prints3spaces,3'w'wwwi = 2: prints2spaces,5'w'wwwwwi = 3: prints1space,7'w'wwwwwwwi = 4: prints0spaces,9'w'wwwwwwwww
- Output Pattern Analysis for Input character
Comprehensive Summary of Looping Concepts
Loop Structure Classification:
while: Reserved word. Pre-test loop. Evaluates condition prior to executing body. Body executes 0 or more times.for: Reserved word. Pre-test loop. Groups initialization, condition check, and update in header. Body executes 0 or more times.do...while: Reserved word. Post-test loop. Evaluates condition after executing body. Body executes at least 1 time.
Control Category Summary:
- Counter-Controlled: Fixed iteration count managed by a counter variable.
- Sentinel-Controlled: Terminated upon reading a specified sentinel value.
- Flag-Controlled: Terminated when a boolean flag variable status changes.
- EOF-Controlled: Terminated upon detecting input stream End-of-File marker (
cin.eof(), triggered byCtrl+zorCtrl+d).
Flow Modification Summary:
break: Instantly terminates the loop structure.continue: Skips the remaining body statements for the current pass and advances directly to the next iteration (evaluatesupdate_stmtfirst inforloops).