Welcome to Program Control Structures

Welcome! In this chapter of AS 1: Introduction to Object Oriented Development, we explore Program Control Structures. Think of control structures as the traffic signs, roundabouts, and traffic lights of your code. By default, a computer executes instructions strictly from top to bottom. Control structures allow your code to make decisions, repeat actions, or jump between blocks of logic. Mastering these fundamentals is essential for writing algorithms, building robust software, and succeeding in your CCEA AS Level examination.


1. The Three Fundamental Building Blocks

Every computer algorithm, no matter how complex, is constructed using three primary logical structures:

1. Sequence: Statements execute strictly line-by-line in sequential order from top to bottom, one after the other, unless altered by selection or iteration.

2. Selection (Branching): The program makes a decision based on a condition, choosing which branch of code to execute.

3. Iteration (Looping): The program repeats a block of code multiple times, either for a fixed count or until a specific condition changes.

Analogy: Imagine baking a cake. Sequence is following the recipe steps in order. Selection is checking: "If you have strawberries, decorate with strawberries; else, use chocolate." Iteration is: "Stir the batter until smooth."

Key Takeaway: Sequence runs in straight lines, Selection chooses a path, and Iteration repeats a path.


2. Selection Structures (Making Decisions)

Selection allows software to respond dynamically to different inputs and conditions.

A. Single and Dual Alternative (if and if...else)

The simplest form of selection evaluates a Boolean condition (an expression that results in either true or false):

Single Branch (if): If the condition is true, the code block runs. If false, the code inside is skipped entirely.

Dual Branch (if...else): If the condition is true, the if block runs. If false, execution automatically branches to the else block.

B. Multiple Alternative / Nested Selection (if...else if...else)

When you have several mutually exclusive conditions to test, you cascade them. The program tests conditions sequentially from top to bottom. As soon as one condition evaluates to true, its block executes, and the rest of the chain is skipped. An optional final else acts as a default catch-all if no conditions match.

C. Multi-way Selection (switch / select case)

A switch statement tests a single expression against discrete match values known as case labels.

The break statement: In languages like C# and Java, a break; statement is required at the end of each case block to terminate execution of the switch construct and prevent accidental "fall-through" into subsequent cases.

The default label: An optional catch-all block that executes if none of the explicit case values match the input expression.

Key Takeaway: Use if...else when evaluating ranges or complex Boolean logic; use switch when comparing a single variable against specific, discrete matching values.


3. Iteration Structures (Repeating Code)

Loops allow us to execute a block of statements repeatedly without writing duplicate code.

A. Definite Iteration: Count-Controlled (for loop)

Used when the exact number of repetitions is known before entering the loop (e.g., repeating an action exactly \(10\) times). A standard for loop contains three critical components:

1. Initialisation: Sets the starting value of the loop counter (e.g., int i = 0).

2. Continuation Condition: A Boolean condition checked before every iteration (e.g., i < n).

3. Step / Increment Expression: Updates the counter after every iteration (e.g., i++).

B. Indefinite Iteration: Pre-Condition (while loop)

Used when the number of iterations is not known in advance, but depends on a condition tested before each pass:

• The Boolean condition is evaluated before entering the loop body.

Minimum Executions: \(0\). If the condition is initially false, the loop body will not execute even once.

C. Indefinite Iteration: Post-Condition (do...while loop)

Used when the code must execute at least once before checking the continuation condition (for example, displaying a menu or prompting a user for input):

• The loop body executes first, and the condition is evaluated at the bottom (post-test).

Minimum Executions: \(1\). Because the test is at the end, the body is guaranteed to run at least once.

D. Collection Iteration (foreach loop)

Iterates sequentially through every item in an array or collection/list from start to finish without requiring an explicit counter variable or index tracking.

Quick Review: Pre-test vs. Post-test Summary
while (Pre-test) \(\implies\) Checks first \(\implies\) Minimum executions: \(0\)
do...while (Post-test) \(\implies\) Checks after \(\implies\) Minimum executions: \(1\)


4. Operators, Boolean Logic, and Scope

Relational and Logical Operators

Control structures rely on comparisons and logic to make decisions:

Relational Operators: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to).

Logical Operators:

- && (Logical AND): Evaluates to true only if both operands are true.

- || (Logical OR): Evaluates to true if at least one operand is true.

- ! (Logical NOT): Inverts the Boolean value (e.g., !true becomes false).

Compound Assignment Operators: ++ (increment by \(1\)), -- (decrement by \(1\)), +=, -=, *=, /=, %= (modulus assignment).

Short-Circuit Evaluation

Modern compilers optimize logical expressions using short-circuit evaluation:

• In an && expression: If the first operand is false, the entire expression cannot possibly be true. The second operand is not evaluated.

• In an || expression: If the first operand is true, the entire expression is already true. The second operand is skipped.

Variable Scope and Lifetime

Block Scope: Variables declared inside selection or iteration blocks (between opening { and closing } braces) are local to that specific block. They cannot be accessed or modified once execution moves outside those enclosing braces.


5. Algorithmic Tools: Trace Tables (Dry Running)

A trace table is a systematic technique used to manually step through an algorithm line-by-line to track variable values and determine program output without running it on a computer.

Standard CCEA Trace Table Format

When constructing or completing trace tables in exam questions, columns typically include:

1. Control variables / Loop counters: Tracking values like i or count.

2. Conditional evaluations: Recording the result (True or False) of tests such as i < 3.

3. Data variables: Tracking totals, accumulators, or user inputs.

4. Program Output: Exact values sent to the Console or display screen.

Exam Tip for Trace Tables: Only record values when they change! Step through line-by-line sequentially and never jump ahead to guess values.


6. Common Exam Pitfalls to Avoid

1. Assignment vs. Equality Check: Confusing = (which assigns a value to a variable) with == (which tests if two values are equal). Inside an if condition, always use == for comparison!

2. Off-by-One Errors: Watch your loop boundaries carefully. For instance, in an array of size \(n\), indices run from \(0\) to \(n - 1\). Using i <= n instead of i < n will attempt to access an invalid index outside the array bounds.

3. Infinite Loops: In a while loop, always make sure the loop counter or sentinel condition is updated inside the loop body. If the control variable never changes, the condition remains permanently true, creating a non-terminating loop.

4. Missing break; in switch: Omitting break; at the end of a case block causes syntax errors in C# or unintended fall-through execution into subsequent cases.

5. Choosing the Wrong Loop Construct: If a task requires input validation that prompts the user first and checks validity second, choose a post-test do...while loop, not a while loop.


Chapter Summary

Sequence: Uninterrupted, step-by-step execution from top to bottom.
Selection: Branching using if, if...else, if...else if...else, and switch.
Iteration: Repeating code using for (count-controlled), while (pre-test, min \(0\) passes), do...while (post-test, min \(1\) pass), and foreach (collections).
Logic: && and || employ short-circuit evaluation.
Dry Running: Trace tables track loop counters, conditions (True/False), variables, and console output sequentially.