Programming Control Structures

Advanced

All program logic is built from three control structures: sequence executes step by step, selection branches on a condition, and iteration repeats; combined with variables, assignment and Boolean conditions, pseudocode expresses language-neutral algorithms.

For:Secondary 5 Information & Communication Technology · Unit:Programming concepts · Lesson 5 of 6 in the learning path

After this lesson, you can:
  • A variable is a named data location; assignment stores the right-hand result into the left-hand variable.
  • Three structures: sequence runs step by step, selection branches on conditions, iteration repeats — and they nest freely.
  • Known repeats take a count-controlled loop, unknown ones a condition-controlled loop; the loop variable must update every pass.
文體:科技知識說明文有聲朗讀

文體小知識:科技知識說明文——講解變量與賦值的基礎上,剖析順序、分支、循環三種控制結構,以偽代碼訓練語言中立的程式邏輯。

資訊及通訊科技Information & Communication Technology
Before this lesson you should know: Algorithms and Flowcharts

§Text Passage

1A program processes data: a variable is a named location holding data, assignment puts data into it — setting a total to zero, say — and control structures arrange the order of the processing instructions. Both theory and practice show that just three basic structures — sequence, selection and iteration — suffice to write a program of any logic.

2Sequence is the most basic structure: instructions execute one by one in written order, the next starting only after the previous finishes. Simple as it looks, order is critical — marks must be entered before the total is computed; likewise, swapping two variables needs a third temporary variable, and getting the order wrong loses data.

3Selection lets a program choose paths by condition: a single-way branch runs a block only when the condition holds; a two-way branch takes one path if it holds and another if not; multi-way and nested branches handle more than two cases, such as grading marks into grades A to D.

4Iteration repeats a block: a count-controlled loop suits a known number of repeats, such as processing thirty class marks one by one; a condition-controlled loop suits repeats decided by a condition, such as asking for input until the password is right. The loop variable must be updated inside the loop, or the condition never changes and the loop becomes infinite.

5Conditions are built from comparison and logical operators and evaluate to Boolean values — true or false only; compound conditions combine them with AND, OR and NOT. The three structures nest freely: a selection inside a loop, a loop inside a branch — layered together, they are the complete toolkit for real problems.

1Summary 重點摘要

All program logic is built from three control structures: sequence executes step by step, selection branches on a condition, and iteration repeats; combined with variables, assignment and Boolean conditions, pseudocode expresses language-neutral algorithms.

2Vocabulary cards Vocabulary

v
variable變量

A named location holding data whose value may change while the program runs.

a
assignment賦值

The act of storing a value or a computed result into a variable, e.g. setting total to total plus mark.

s
sequence順序結構

The control structure in which instructions execute one by one in written order; the most basic of the three.

s
selection (branch)分支結構(選擇結構)

The structure choosing a path by whether a condition holds, in single-way, two-way and multi-way forms.

l
loop (iteration)循環結構

The structure repeating a block of instructions, as a count-controlled loop with known repeats or a condition-controlled loop.

c
condition條件

An expression built from comparison and logical operators, evaluating to true or false only, used in selections and loops.

B
Boolean布爾

The data type with only two values, true and false, underlying all condition testing.

o
operator運算符

A symbol performing an operation: arithmetic operators, comparison operators and logical operators (AND, OR, NOT).

i
infinite loop死循環(無限循環)

A loop that never ends because its condition stays true, usually because the loop variable is never updated.

n
nesting巢狀

Placing one control structure inside another, e.g. a selection inside a loop, layering simple structures into complex logic.

3Step by step Steps

  1. Step 1: Variables and assignmentA variable can be pictured as a labelled storage cell whose contents the program reads or changes at any time; assignment puts data into it, written with the variable on the left and a value or expression on the right. Assignment overwrites the old value, and the right-hand expression may reference the variable itself: setting total to total plus mark updates the running total with a new mark. For example, beginners ask how 'total equals total plus mark' can be true — the right side is evaluated with the old value first and stored back on the left, which is exactly how accumulation works.
  2. Step 2: Sequence and the importance of orderSequence executes instructions one by one in written order; the next instruction starts only after the previous one finishes. A wrong order ruins the result: enter the size and the marks before computing the average; set the counter to zero before accumulating. The classic case is swapping two variables: setting A to B directly destroys the original value of A; the correct way is to store A in a temporary variable, then set A to B, then set B to the temporary. For example, stepping through fifty and twenty shows the temporary preserving the fifty, completing the swap.
  3. Step 3: Selection — single-way and two-waySelection chooses paths by condition. A single-way branch runs a block only when the condition holds and skips it otherwise — adding one to the pass count only when a mark is at least fifty. A two-way branch arranges both sides: one block when the condition holds, another when it fails — outputting pass or fail accordingly; exactly one of the two paths runs, never both, never neither. For example, judging pass or fail suits a two-way branch because both outcomes need handling, while crediting only passing marks suits a single-way branch — the requirement decides which form to use.
  4. Step 4: Multi-way and nested branchesWith more than two cases, use nested branches judging layer by layer, or a multi-way branch sorting at once. For grading: at least eighty is grade A, at least sixty is B, the rest is C — nested, first test whether the mark reaches eighty; if yes, grade A; if not, test whether it reaches sixty; if yes, grade B; otherwise C. Nesting must keep the layers clear: the inner test runs only when the outer condition fails. For example, the order of tests cannot be shuffled — testing sixty first would grade an eighty as B; judging from strictest to loosest is the basic principle of multi-way branching.
  5. Step 5: Conditions and Boolean logicConditions are built from comparison operators — greater than, less than, equal to, greater than or equal to, less than or equal to, not equal to — and evaluate to Boolean values, true or false only. Complex conditions combine them with logical operators: AND requires both sides to hold; OR requires either side; NOT flips true to false. For example, 'mark at least fifty AND mark below sixty' pins the range fifty to fifty-nine, while 'aged twelve or above OR at least 1.4 metres tall' needs only one side; before writing a condition, decide whether both parts or either part must hold.
  6. Step 6: Count-controlled and condition-controlled loopsIteration comes in two forms. A count-controlled loop suits a known number of repeats: the counter runs from one to the class size, entering and accumulating one mark per pass — thirty students means exactly thirty passes. A condition-controlled loop, headed by WHILE, suits repeats decided by a condition: the condition is checked before every pass, and the loop continues only while it holds — asking for the password until it is correct. The two are interchangeable, but a known count reads clearer as a count-controlled loop. For example, averaging a class uses counting since the size is known, while input that stops only when the user clicks stop suits a condition-controlled loop.
  7. Step 7: Causes of infinite loops and combining the structuresIf a condition-controlled loop never updates the variable its condition depends on, the condition stays true forever and the program never ends — an infinite loop; forgetting to add one to the counter while the condition compares it with the class size is the usual cause. The remedy is updating the variable inside every pass so the condition eventually fails. The three structures nest freely: a selection inside a loop judges passes, a loop inside a branch retries input. For example, a class statistics program is sequence for initialising, a loop for reading, a selection inside the loop counting passes, and sequence again for output — any complex logic is layered from these same pieces.

4Diagrams Diagrams

偽代碼 vs 流程圖:同一邏輯兩種寫法偽代碼 pseudocodeINPUT scoreIF score >= 50 THENOUTPUT "合格"ELSEOUTPUT "要加油"流程圖 flowchart開始≥50?顯示結果是否偽代碼=用普通字寫程式邏輯(唔使理語法);流程圖=畫出嚟睇流程寫程式前先寫偽代碼/畫圖——諗清楚邏輯先至落手,事倍功半
Fig. 1: Pseudocode and flowcharts

5Worked example Example

Application task: a class finishes a test, the number of students being N. Write pseudocode to input every class mark one by one and output the average and the number of passes (fifty or above passes), naming the control structures used and the variables that must be initialised.

  1. Sequence initialises: INPUT N; set the total T, the pass count P and the counter C to zero — all three must be initialised, or accumulation and counting cannot start.
  2. A loop reads the class: WHILE C is less than N, repeat — INPUT the mark S, and set T to T plus S.
  3. A selection judges passes: inside the loop, if S is at least fifty, set P to P plus one (single-way); at the end of every pass set C to C plus one, keeping the loop finite and avoiding an infinite loop.
  4. Sequence outputs: after leaving the loop, set the average A to T divided by N, and OUTPUT A and P.
  5. Answer: Pseudocode: INPUT N; set T to 0; set P to 0; set C to 0; WHILE C < N: INPUT S; set T to T + S; IF S >= 50 THEN set P to P + 1; set C to C + 1; ENDWHILE; set A to T / N; OUTPUT A; OUTPUT P. Structures used: sequence (initialising and output), iteration (reading the class), selection (judging passes); the variables that must be initialised are T, P and C.

6Common mistakes Mistakes

✗ Treating an assignment as a mathematical equation and objecting that 'total set to total plus mark' cannot hold.
✓ Assignment is an action, not an equation: the right side is computed with the old value and stored back — exactly how accumulation is written.
✗ Forgetting to update the counter or loop variable inside the loop.
✓ Every pass must update the variable the condition depends on, e.g. adding one to the counter, or the condition stays true forever — an infinite loop.
✗ Ordering grade tests from loose to strict, testing sixty before eighty.
✓ Multi-way tests run strict to loose: test the high threshold first — eighty gives grade A — then sixty gives B; the order must not be shuffled.
✗ Accumulating into variables that were never initialised.
✓ Accumulating variables such as totals and counters must be initialised to zero first, or the starting point is undefined and the result wrong.
✗ Believing both paths of a branch execute one after the other.
✓ A two-way branch takes exactly one path: one when the condition holds, the other when it fails — never both.

7Quick check Quick check

Q1What are the three basic control structures?

Q2The class size is known and every mark must be entered and totalled. Which loop suits this, and why?

Q3What happens if 'add one to the counter' is missing inside a loop?

Q4Which range of marks does 'mark at least fifty AND mark below sixty' cover?

Q5Why does swapping variables A and B need a third temporary variable?

8Recap Recap

  • A variable is a named data location; assignment stores the right-hand result into the left-hand variable.
  • Three structures: sequence runs step by step, selection branches on conditions, iteration repeats — and they nest freely.
  • Known repeats take a count-controlled loop, unknown ones a condition-controlled loop; the loop variable must update every pass.
  • Conditions yield Boolean values, built from comparison operators combined with AND, OR and NOT.
  • Multi-way tests run from strict to loose; accumulating variables must be initialised to zero before use.

Other subjects in this grade

Same subject, other grades