Program Control Structures: Sequence, Selection, and Iteration | 程序控制结构:顺序、分支与循环

📚 Program Control Structures: Sequence, Selection, and Iteration | 程序控制结构:顺序、分支与循环

Program control structures define the order in which instructions are executed within a program. They are the fundamental building blocks of all algorithms, determining the logical flow from input to output. Understanding these structures is essential for writing efficient, readable, and maintainable code in any programming language.

程序控制结构定义了程序中指令执行的顺序,它们是所有算法的基本构建模块,决定了从输入到输出的逻辑流程。理解这些结构对于用任何编程语言编写高效、可读且可维护的代码都至关重要。


1. The Three Fundamental Control Structures | 三种基本控制结构

In 1966, computer scientists Böhm and Jacopini proved that any computable function can be implemented using just three control structures: sequence, selection, and iteration. This theorem, known as the Structured Program Theorem, forms the theoretical foundation of structured programming.

1966年,计算机科学家Böhm和Jacopini证明了任何可计算函数都可以仅用三种控制结构来实现:顺序、分支和循环。这个定理被称为结构化程序定理,构成了结构化编程的理论基础。

Sequence refers to executing statements one after another in a linear order. Selection allows the program to choose between different paths based on conditions. Iteration enables a block of code to be executed repeatedly until a specific condition is met. Together, these three structures can express any algorithm.

顺序结构指语句按线性次序逐条执行;分支结构允许程序根据条件在不同路径间做出选择;循环结构使代码块可以重复执行,直到满足特定条件。这三种结构组合起来可以表达任何算法。


2. Sequence Structure | 顺序结构

Sequence is the simplest and most natural control structure. Statements are executed from top to bottom, one after another, without any branching or repetition. Each statement is processed exactly once, in the exact order they appear in the source code. This is analogous to following a recipe: you complete each step in order before moving to the next.

顺序结构是最简单、最自然的控制结构。语句从上到下逐条执行,没有任何分支或重复。每条语句恰好被执行一次,严格按照它们在源代码中出现的顺序处理。这类似于按照食谱操作:先按顺序完成每一步,再进入下一步。

For example, consider a simple program that calculates the area of a rectangle:

例如,考虑一个计算矩形面积的简单程序:

INPUT length
INPUT width
area ← length × width
OUTPUT area

Here, each line executes in sequence: first the length is read, then the width, then the area is calculated, and finally the result is displayed. If the order were changed, the program would produce incorrect results or fail to run altogether.

在这里,每行按顺序执行:首先读取长度,然后读取宽度,然后计算面积,最后显示结果。如果改变顺序,程序可能会产生错误结果,甚至无法运行。

Sequence structures are straightforward but limited on their own — real programs require the ability to make decisions and repeat operations, which brings us to the other two structures.

顺序结构本身简单但有限——真实程序需要做出决策和重复操作的能力,这就引入了另外两种结构。


3. Selection: IF-THEN-ELSE | 分支结构:IF-THEN-ELSE

Selection, also called conditional branching, allows the program to execute different statements depending on whether a condition is true or false. The most common selection construct is the IF-THEN-ELSE statement. The condition is evaluated as a Boolean expression, yielding either TRUE or FALSE.

分支结构,也称为条件分支,允许程序根据条件为真或假来执行不同的语句。最常见的分支构造是IF-THEN-ELSE语句。条件被求值为布尔表达式,结果为TRUE或FALSE。

The general syntax in pseudocode is:

伪代码中的一般语法为:

IF condition THEN
    statement(s) A
ELSE
    statement(s) B
ENDIF

If the condition evaluates to TRUE, statement(s) A executes; if FALSE, statement(s) B executes. Only one branch is ever executed — never both. This ensures mutually exclusive paths through the program.

如果条件求值为TRUE,则执行语句A;如果为FALSE,则执行语句B。两个分支中只有一个会被执行——绝不会同时执行两者。这确保了程序路径的互斥性。

A practical example: a program that determines whether a student has passed an exam.

一个实际例子:判断学生是否通过考试的程序。

INPUT score
IF score ≥ 50 THEN
    OUTPUT “Pass”
ELSE
    OUTPUT “Fail”
ENDIF

The IF statement can also appear without an ELSE clause, known as an IF-THEN or single-branch selection. In this case, if the condition is FALSE, no action is taken and execution continues with the next statement after ENDIF.

IF语句也可以不带ELSE子句,称为IF-THEN或单分支选择。在这种情况下,如果条件为FALSE,则不执行任何操作,程序继续执行ENDIF之后的下一语句。


4. Selection: CASE (Switch) Statement | 分支结构:CASE(开关)语句

When multiple distinct values of a single variable need to be checked, nested IF-ELSE statements become verbose and difficult to read. The CASE statement (called SWITCH in many languages) provides a cleaner alternative. It evaluates an expression and compares it against multiple discrete values.

当需要检查单个变量的多个不同取值时,嵌套的IF-ELSE语句会变得冗长且难以阅读。CASE语句(在许多语言中称为SWITCH)提供了一种更清晰的选择。它求值一个表达式,并将其与多个离散值进行比较。

Pseudocode syntax:

伪代码语法:

CASE OF grade
    ‘A’: OUTPUT “Excellent”
    ‘B’: OUTPUT “Good”
    ‘C’: OUTPUT “Average”
    OTHERWISE: OUTPUT “Needs improvement”
ENDCASE

The CASE structure evaluates the variable grade once and matches it against each listed value. The OTHERWISE (or DEFAULT) clause handles any value not explicitly listed. This is more efficient than multiple IF statements because the expression is evaluated only once.

CASE结构对变量grade求值一次,并将其与列出的每个值进行匹配。OTHERWISE(或DEFAULT)子句处理未明确列出的任何值。这比多个IF语句更高效,因为表达式只被求值一次。

A CASE statement is equivalent to a chain of IF-ELSE-IF statements but offers better readability. However, CASE can only test for equality with discrete values — it cannot handle relational operators like greater-than or less-than directly.

CASE语句等价于一串IF-ELSE-IF语句,但提供了更好的可读性。然而,CASE只能测试与离散值的相等性——不能直接处理大于或小于等关系运算符。


5. Iteration: The FOR Loop | 循环结构:FOR循环

Iteration, also called looping or repetition, allows a block of statements to be executed multiple times. The FOR loop is used when the number of iterations is known in advance. It uses a counter variable that is incremented or decremented with each pass through the loop.

循环结构,也称为重复或迭代,允许一个语句块被执行多次。当迭代次数事先已知时,使用FOR循环。它使用一个计数器变量,每次通过循环时递增或递减。

General pseudocode form:

一般伪代码形式:

FOR counter ← initial_value TO final_value [STEP increment]
    statement(s)
NEXT counter

For example, to print the numbers 1 through 5:

例如,打印数字1到5:

FOR i ← 1 TO 5
    OUTPUT i
NEXT i

This loop executes five times: when i = 1, 2, 3, 4, and 5. After the final iteration, i becomes 6, which exceeds the final value, and the loop terminates. The STEP keyword allows the counter to increment by values other than 1, including negative values for counting down.

这个循环执行五次:当i = 1、2、3、4和5时。在最后一次迭代后,i变为6,超过了最终值,循环终止。STEP关键字允许计数器以1以外的值递增,包括用于倒数的负值。

FOR loops are ideal when the exact number of repetitions is known at the start. Common applications include iterating through arrays, performing calculations a fixed number of times, and generating sequences.

当循环开始时确切的重次数已知时,FOR循环是理想选择。常见应用包括遍历数组、执行固定次数的计算以及生成序列。


6. Iteration: WHILE and REPEAT-UNTIL Loops | 循环结构:WHILE和REPEAT-UNTIL循环

In many situations, the number of iterations is not known in advance. Instead, the loop must continue until a certain condition is met. Two constructs handle this: the WHILE loop and the REPEAT-UNTIL loop. They differ in when the condition is tested.

在许多情况下,迭代次数事先并不知道。相反,循环必须持续直到满足某个条件。有两种构造处理这种情况:WHILE循环和REPEAT-UNTIL循环。它们的区别在于条件在何时被测试。

The WHILE loop tests the condition before each iteration. If the condition is initially FALSE, the loop body never executes. This is a pre-test or entry-controlled loop.

WHILE循环在每次迭代之前测试条件。如果条件最初为FALSE,循环体永远不会执行。这是前置测试或入口控制循环。

WHILE condition
    statement(s)
ENDWHILE

The REPEAT-UNTIL loop tests the condition after each iteration. Therefore, the loop body always executes at least once. This is a post-test or exit-controlled loop.

REPEAT-UNTIL循环在每次迭代之后测试条件。因此,循环体至少执行一次。这是后置测试或出口控制循环。

REPEAT
    statement(s)
UNTIL condition

A key distinction: in a WHILE loop, the loop continues while the condition is TRUE and stops when it becomes FALSE. In a REPEAT-UNTIL loop, the loop continues until the condition becomes TRUE — the semantics are inverted. One common error among students is confusing these two termination conditions.

关键区别:在WHILE循环中,当条件为TRUE时循环继续,当变为FALSE时停止。在REPEAT-UNTIL循环中,循环一直持续直到条件变为TRUE——其语义是相反的。学生中常见的错误是混淆这两种终止条件。


7. Comparison of Loop Structures | 循环结构的比较

Feature | 特性 FOR WHILE REPEAT-UNTIL
Iterations known in advance | 迭代次数预先已知 Yes | 是 No | 否 No | 否
Condition tested | 条件测试时机 N/A (counter-based) | 不适用(基于计数器) Before loop body | 循环体之前 After loop body | 循环体之后
Minimum executions | 最少执行次数 0 (if range empty) | 0(若范围为空的) 0 | 0 1 | 1
Termination condition | 终止条件 Counter exceeds range | 计数器超出范围 Condition becomes FALSE | 条件变为FALSE Condition becomes TRUE | 条件变为TRUE

Choosing the correct loop structure depends on the problem context. Use FOR when the count is known; use WHILE when the loop may execute zero or more times based on a condition; use REPEAT-UNTIL when the loop must execute at least once.

选择正确的循环结构取决于问题情境。当次数已知时使用FOR;当循环可能基于条件执行零次或多次时使用WHILE;当循环必须至少执行一次时使用REPEAT-UNTIL。


8. Nested Control Structures | 嵌套控制结构

Control structures can be nested inside one another to handle complex logic. For example, a loop may contain an IF statement, or two loops may be nested to iterate through a two-dimensional array. Proper indentation is crucial for readability when nesting structures.

控制结构可以相互嵌套以处理复杂逻辑。例如,循环中可以包含IF语句,或者两个循环可以嵌套以遍历二维数组。嵌套结构时,正确的缩进对于可读性至关重要。

Consider a program that prints a multiplication table:

考虑一个打印乘法表的程序:

FOR i ← 1 TO 5
    FOR j ← 1 TO 5
        OUTPUT i × j
    NEXT j
NEXT i

The inner loop (j) completes all its iterations for each single iteration of the outer loop (i). Thus, the OUTPUT statement executes 5 × 5 = 25 times. This demonstrates multiplicative growth in execution count for nested loops.

内层循环(j)在每次外层循环(i)的单次迭代中完成其全部迭代。因此,OUTPUT语句执行5 × 5 = 25次。这展示了嵌套循环中执行次数的乘法增长。

Nesting can extend to any depth, but in practice, more than three levels of nesting become difficult to debug and maintain. Algorithms that require deep nesting should often be refactored into separate functions or procedures.

嵌套可以延伸到任意深度,但在实践中,超过三层的嵌套会变得难以调试和维护。需要深度嵌套的算法通常应被重构为独立的函数或过程。


9. Pseudocode and Flowchart Representation | 伪代码与流程图表示

In A-Level examinations, students are expected to represent control structures in both pseudocode and flowcharts. Each structure has a distinct visual representation in flowchart notation.

在A-Level考试中,学生需要用伪代码和流程图两种方式表示控制结构。每种结构在流程图符号中都有独特的视觉表示。

Sequence is drawn as a series of rectangular process boxes connected by arrows in a vertical line. Selection is represented by a diamond-shaped decision symbol with one entry point and two exit paths labeled TRUE and FALSE. Iteration is shown using a loop symbol or by drawing arrows that cycle back to a decision or process box.

顺序结构绘制为一系列由箭头垂直连接的矩形处理框。分支结构用菱形决策符号表示,有一个入口点和两条分别标为TRUE和FALSE的出口路径。循环结构使用循环符号表示,或通过绘制返回到决策或处理框的循环箭头来表示。

Structure | 结构 Flowchart Symbol | 流程图符号 Pseudocode Keyword | 伪代码关键字
Sequence | 顺序 Rectangle (process) | 矩形(处理框) Sequential statements | 顺序语句
Selection | 分支 Diamond (decision) | 菱形(决策框) IF, CASE
Iteration | 循环 Loop boundary / back arrow | 循环边界或回箭 FOR, WHILE, REPEAT

In all A-Level exam boards (including Cambridge International and Pearson Edexcel), pseudocode has a standardized syntax that students must follow. Always use clear, unambiguous variable names and proper keywords such as ENDIF, ENDWHILE, and NEXT.

在所有A-Level考试局(包括剑桥国际和培生爱德思)中,伪代码都有标准化的语法要求。务必使用清晰无歧义的变量名以及正确的关键字,如ENDIF、ENDWHILE和NEXT。


10. Common Errors and Exam Pitfalls | 常见错误与考试陷阱

Students frequently lose marks on control structure questions due to several recurring mistakes. Recognizing and avoiding these pitfalls is critical for achieving high marks in the computer science examination.

由于几个反复出现的错误,学生经常在控制结构题目上失分。识别并避免这些陷阱对于在计算机科学考试中获得高分至关重要。

  • Off-by-one errors: Using the wrong loop boundary, such as iterating from 1 to n when it should be 0 to n−1, or vice versa. Always verify the exact start and end values.

    差一错误:使用错误的循环边界,例如当应该从0到n−1时使用了从1到n迭代,反之亦然。始终仔细核实精确的起始值和结束值。

  • Infinite loops: Failing to update the loop variable inside a WHILE loop, or writing a condition that never becomes FALSE. For example, WHILE x > 0 with no statement that decreases x will loop forever.

    无限循环:未在WHILE循环内更新循环变量,或编写了永远不会变为FALSE的条件。例如,WHILE x > 0但没有减少x的语句将永远循环。

  • Confusing REPEAT-UNTIL with WHILE: Remember that WHILE continues while TRUE, but REPEAT-UNTIL stops when TRUE. They are logically complementary conditions.

    混淆REPEAT-UNTIL与WHILE:记住WHILE在TRUE时继续,而REPEAT-UNTIL在TRUE时停止。它们在逻辑上是互补的条件。

  • Missing ENDIF/ENDWHILE: In written pseudocode, forgetting to close a structure. Exam markers deduct marks for incomplete syntax.

    遗漏ENDIF/ENDWHILE:在书写伪代码时,忘记关闭结构。考官会因语法不完整而扣分。

  • Using CASE for relational conditions: The CASE statement can only match discrete values. Attempting to express “grade > 70” in a CASE statement is incorrect — use IF-ELSE instead.

    将CASE用于关系条件:CASE语句只能匹配离散值。试图在CASE语句中表达”grade > 70″是错误的——应改用IF-ELSE。

Additionally, always trace through your algorithm with sample inputs before finalizing your answer. Manual dry-running catches most logical errors and demonstrates methodical thinking to examiners.

此外,在定稿答案之前,务必用样本输入手动跟踪你的算法。手工走查(dry-run)能发现大多数逻辑错误,并向考官展示有条理的思维。


11. Real-World Applications | 实际应用

Control structures appear in virtually every software system. A banking application uses sequence to process transactions step by step, selection to verify account balances and authorise or reject payments, and iteration to process multiple transactions in a batch.

控制结构出现在几乎所有软件系统中。银行应用程序使用顺序结构逐步处理交易,使用分支结构验证账户余额并授权或拒绝付款,使用循环结构批量处理多笔交易。

A video game loop is a classic example of iteration combined with selection: the game repeatedly checks for player input (WHILE playing), processes game logic, renders frames, and tests conditions such as collision detection or score thresholds. Without iteration, the game would only display a single static frame.

视频游戏循环是循环与分支结合的经典例子:游戏重复检查玩家输入(WHILE游戏进行中),处理游戏逻辑,渲染帧,并测试如碰撞检测或分数阈值等条件。没有循环,游戏只能显示一帧静态画面。

In data processing, iteration is used to traverse collections of data — summing totals, finding maximum values, or searching for specific records. Selection filters which records to process, and sequence ensures the steps are performed in the correct order, such as opening a file before reading it.

在数据处理中,循环用于遍历数据集合——求和、查找最大值或搜索特定记录。分支用于过滤哪些记录需要处理,顺序确保了步骤按正确顺序执行,例如在读取文件之前先打开文件。


12. Key Exam Questions and Worked Example | 关键考试题目与例题解析

A common examination question asks students to determine the output of a given pseudocode fragment. Consider the following:

一个常见的考试题目要求确定给定伪代码片段的输出。考虑以下代码:

total ← 0
FOR count ← 1 TO 4
    IF count MOD 2 = 0 THEN
        total ← total + count
    ENDIF
NEXT count
OUTPUT total

Tracing through: count = 1 → 1 MOD 2 = 1, not even, skip. count = 2 → 2 MOD 2 = 0, even, total = 0 + 2 = 2. count = 3 → 3 MOD 2 = 1, skip. count = 4 → 4 MOD 2 = 0, even, total = 2 + 4 = 6. The OUTPUT is 6.

逐步跟踪:count = 1 → 1 MOD 2 = 1,不是偶数,跳过。count = 2 → 2 MOD 2 = 0,是偶数,total = 0 + 2 = 2。count = 3 → 3 MOD 2 = 1,跳过。count = 4 → 4 MOD 2 = 0,是偶数,total = 2 + 4 = 6。输出为6。

Another typical question asks students to write pseudocode for a given problem. For instance: “Write a program that reads numbers until a negative number is entered, then outputs the sum of all positive numbers read.” A WHILE loop is appropriate since the number of inputs is unknown:

另一个典型题目要求学生为给定问题编写伪代码。例如:”编写一个程序,读取数字直到输入负数,然后输出所有正数之和。”由于输入次数未知,适合使用WHILE循环:

sum ← 0
INPUT num
WHILE num ≥ 0
    sum ← sum + num
    INPUT num
ENDWHILE
OUTPUT sum

Notice that the first INPUT must occur before the loop, allowing the WHILE condition to be evaluated. This pattern — reading before and inside the loop — is known as a “priming read” and is an important technique for sentinel-controlled loops.

注意第一次INPUT必须在循环之前,以便WHILE条件能够被求值。这种在循环前和循环内都读入的模式称为”预读”(priming read),对于哨兵控制循环是一项重要技术。

When writing solutions, always check: does your loop terminate for all valid inputs? Are all variables initialised? Does the output match the problem specification? These checks may take only 30 seconds but can save valuable marks.

在撰写解答时,始终检查:你的循环对所有有效输入都会终止吗?所有变量都已初始化吗?输出是否与题目规范匹配?这些检查只需30秒,却能节省宝贵的分数。


Mastering the three fundamental control structures — sequence, selection, and iteration — is the cornerstone of programming proficiency. For the A-Level computer science examination, ensure you can both analyse existing code and construct original solutions using these structures. Practice tracing code manually, pay attention to loop boundaries and condition semantics, and always write structured, properly terminated pseudocode. With solid command of control structures, you will be well-prepared for any programming-related examination question.

掌握三种基本控制结构——顺序、分支和循环——是编程熟练的基石。对于A-Level计算机科学考试,确保你既能分析现有代码,也能使用这些结构构建原创解决方案。练习手动跟踪代码,注意循环边界和条件语义,始终编写结构化、正确终止的伪代码。扎实掌握控制结构,你将为任何编程相关的考试题目做好充分准备。

Published by TutorHao | Computer Science Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading