Operators, Program Structures and Subprograms | 运算符、程序结构与子程序

📚 Operators, Program Structures and Subprograms | 运算符、程序结构与子程序

In Edexcel A-Level Computer Science, a solid grasp of programming fundamentals – covering operators, control flow and modular design – is essential for both the written examination and the practical project. This article systematically unpacks the building blocks every programmer must command: from arithmetic and logical operators, through selection and iteration structures, to subprograms and recursion. Each concept is illustrated with pseudocode as used in Edexcel assessments, ensuring that learners can confidently apply them under exam conditions.

在 Edexcel A-Level 计算机科学课程中,牢固掌握编程基础——涵盖运算符、控制流和模块化设计——对笔试和实践项目都至关重要。本文系统梳理了每位程序员必须掌握的基础模块:从算术和逻辑运算符,到选择和迭代结构,再到子程序与递归。每个概念均配以 Edexcel 评估中使用的伪代码示例,确保学习者能够在考试中有把握地应用它们。

1. Understanding Operators | 理解运算符

Arithmetic operators handle basic mathematical operations. The standard set includes addition (+), subtraction (-), multiplication (*), division (/), exponentiation (^ or **) and unary negation (-). In many A-Level pseudocode notations, exponentiation is written as ^ (e.g., 2^3 evaluates to 8). While division (/) may yield a real number, Edexcel pseudocode often uses / for floating-point division and DIV for integer division, alongside MOD for the remainder.

算术运算符处理基本数学运算。标准集合包括加法 (+)、减法 (-)、乘法 (*)、除法 (/)、求幂 (^ 或 **) 和一元取负 (-)。在许多 A-Level 伪代码记法中,求幂写作 ^(例如 2^3 计算结果为 8)。虽然除法 (/) 可能产生实数,但 Edexcel 伪代码常用 / 进行浮点除法,DIV 进行整数除法,同时用 MOD 求余数。

Relational (comparison) operators evaluate the relationship between two values and return a Boolean result: equal to (= or ==), not equal to (<> or !=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Edexcel-endorsed pseudocode consistently uses = for equality, <> for inequality, and the standard >, <, >=, <= symbols. These are heavily used in conditional statements and loop conditions.

关系(比较)运算符评估两个值之间的关系并返回布尔结果:等于 (= 或 ==)、不等于 (<> 或 !=)、大于 (>)、小于 (<)、大于等于 (>=) 和小于等于 (<=)。Edexcel 认可的伪代码一贯用 = 表示相等,<> 表示不等,以及标准 >、<、>=、<= 符号。它们被大量用于条件语句和循环条件。

Logical operators combine Boolean expressions: AND (true only if both operands are true), OR (true if at least one operand is true) and NOT (negates the Boolean value). In pseudocode they are written as AND, OR, NOT. Short-circuit evaluation – stopping the evaluation of the second operand when the result is already determined – is a typical compiler behaviour that candidates should recognise. For example, in (x > 5) AND (y < 10), if x is not greater than 5, y < 10 is not evaluated.

逻辑运算符组合布尔表达式:AND(仅当两个操作数均为真时为真)、OR(至少一个操作数为真时为真)和 NOT(对布尔值取反)。在伪代码中它们写作 AND、OR、NOT。短路求值——当结果已可确定时停止对第二个操作数的求值——是候选人应识别的常见编译器行为。例如,在 (x > 5) AND (y < 10) 中,若 x 不大于 5,则不会计算 y < 10。

Many languages also offer bitwise operators (&, |, ~, ^, <<, >>) that manipulate individual bits within integer values. While less common in high-level A-Level pseudocode tasks, understanding them can be useful for low-level data manipulation questions appearing in the ‘Fundamentals of Computer Systems’ section. Edexcel may include them in binary arithmetic and data representation contexts.

许多语言还提供按位运算符(&、|、~、^、<<、>>),用以操作整数值中的各个位。虽然在高级的 A-Level 伪代码任务中较少出现,但理解它们对解答“计算机系统基础”部分中可能出现的低级数据操作问题有所帮助。Edexcel 可能在二进制算术和数据表示上下文中涉及这些运算符。


2. Assignment and String Operators | 赋值与字符串运算符

The assignment operator is represented by a left-pointing arrow ← in Edexcel pseudocode, rather than the equals sign used in many high-level languages. For instance, total ← 0 assigns the value 0 to the variable total. This notation emphasises that assignment is not mathematical equality but an instruction to store a value in a memory location. Candidates must use the arrow consistently in exam responses.

赋值运算符在 Edexcel 伪代码中用左箭头 ← 表示,而非许多高级语言中使用的等号。例如,total ← 0 将值 0 赋给变量 total。这种记法强调赋值并非数学等式,而是一条将值存入内存位置的指令。考生在考试作答中必须一致使用箭头。

String manipulation is a key skill. The concatenation operator – typically the ampersand (&) or plus (+) – joins two strings into one. The length function (LEN(str)) returns the number of characters, while SUBSTRING(str, start, length) extracts a portion. To convert between case, we often use ToUpper(str) and ToLower(str). In Edexcel’s recommended pseudo-code, these operations are defined clearly, so candidates should be familiar with their syntax.

字符串操作是一项关键技能。连接运算符——通常为和号 (&) 或加号 (+)——将两个字符串合并为一个。长度函数(LEN(str))返回字符个数,而 SUBSTRING(str, start, length) 提取一部分。为转换大小写,常使用 ToUpper(str) 和 ToLower(str)。在 Edexcel 推荐的伪代码中,这些操作有明确定义,考生应熟悉其语法。

String comparisons are performed using relational operators, where alphabetical order is usually based on ASCII or Unicode values. Thus, ‘A’ < 'B' is true, but 'a' > ‘Z’ because of the underlying numeric values. When solving problems such as sorting a list of names, understanding how string comparisons work prevents logical errors.

字符串比较使用关系运算符进行,其中字母顺序通常基于 ASCII 或 Unicode 数值。因此,’A’ < 'B' 为真,但 'a' > ‘Z’,因为底层数值的差异。在解决诸如姓名列表排序的问题时,理解字符串比较的工作原理可以避免逻辑错误。


3. Selection Structures: IF Statements | 选择结构:IF 语句

The simplest selection construct is the IF…THEN…ENDIF structure. If the condition evaluates to TRUE, the block of statements executes; otherwise it is skipped. For example: IF score >= 50 THEN grade ← ‘Pass’ ENDIF. In Edexcel pseudocode, the THEN keyword is mandatory and the block finishes with ENDIF. Indentation, while not strictly enforced, greatly enhances readability and is strongly encouraged.

最简单的选择结构是 IF…THEN…ENDIF 结构。若条件求值为 TRUE,则执行语句块;否则跳过。例如:IF score >= 50 THEN grade ← ‘Pass’ ENDIF。在 Edexcel 伪代码中,关键字 THEN 是必须的,语句块以 ENDIF 结束。缩进虽非强制,但能极大提升可读性,并强烈推荐使用。

An IF…THEN…ELSE…ENDIF structure provides two mutually exclusive paths. When the condition is true, the first block executes; otherwise the block after ELSE runs. This is essential for binary decision-making. Nested IF statements place one IF inside another, allowing multi-level conditions. For example, checking a student’s mark and then assigning a letter grade requires nested or multiple conditions.

IF…THEN…ELSE…ENDIF 结构提供两条互斥的路径。条件为真时执行第一个块;否则执行 ELSE 后的代码块。这对二元决策至关重要。嵌套 IF 语句将一个 IF 置于另一个之内,允许实现多级条件。例如,检查学生的分数然后分配字母等级就需要嵌套或多个条件。

The ELSE IF combination (sometimes written as ELSIF or ELSEIF) avoids deep nesting and improves clarity. Edexcel pseudocode often supports ELSE IF as a separate keyword. Take care to close each IF block with its own ENDIF. A common mistake is mismatched ENDIFs, which the examiner will mark as incorrect. Using a trace table to verify logic is highly advisable.

使用 ELSE IF 组合(有时写作 ELSIF 或 ELSEIF)可以避免深层嵌套并提升清晰度。Edexcel 伪代码常支持 ELSE IF 作为独立关键字。注意用对应的 ENDIF 关闭每个 IF 块。一个常见错误是 ENDIF 不匹配,考官会因此扣分。强烈建议使用跟踪表验证逻辑。


4. CASE Statements for Multiple Branches | 用于多分支的 CASE 语句

When a single variable is tested against several possible values, a CASE (or SWITCH) structure is cleaner than multiple ELSE IF blocks. In Edexcel pseudocode, the structure may appear as CASE OF followed by several value : statement options and an optional OTHERWISE clause. After the appropriate block executes, control passes to the end of the CASE.

当需要根据单个变量匹配多个可能值时,CASE(或 SWITCH)结构比多个 ELSE IF 块更简洁。在 Edexcel 伪代码中,该结构可能表现为 CASE OF <变量>,后跟若干 值 : 语句 选项和一个可选的 OTHERWISE 子句。在适当的块执行之后,控制权转移到 CASE 结束处。

A CASE statement is particularly useful when processing menu choices, days of the week, or examination grades. Each branch corresponds to a discrete value or range. For example, CASE OF month could handle each month of the year. Ranges can be expressed as 1..3 : output ‘Q1’, which signals the examiner you understand data-range logic.

CASE 语句在处理菜单选项、星期几或考试等级时特别有用。每个分支对应一个离散值或范围。例如,CASE OF month 可处理一年的每个月份。范围可表示为 1..3 : output ‘Q1’,这向考官表明你理解数据范围逻辑。

Examiners expect candidates to choose the most appropriate structure: IF for Boolean conditions, CASE for discrete value matching. In many A-Level mark schemes, using a CASE statement where an IF would be convoluted is rewarded for efficient design. Ensure you include an OTHERWISE clause to catch unexpected inputs, demonstrating defensive programming.

考官期望考生能选择最合适的结构:IF 用于布尔条件,CASE 用于离散值匹配。在许多 A-Level 评分方案中,在 IF 会变得繁琐的地方使用 CASE 语句会因高效设计而获得奖励。确保包含一个 OTHERWISE 子句来捕获意外输入,以展示防御性编程。


5. Iteration: FOR Loops | 迭代:FOR 循环

A FOR loop executes a block a definite number of times, controlled by a counter variable. In Edexcel pseudocode, the typical syntax is FOR identifier ← start TO finish [STEP increment]. After each iteration, the counter increments by the STEP value (default 1). The loop terminates when the counter passes the finish value. FOR loops are ideal when the number of repetitions is known before the loop starts, such as processing all elements of an array.

FOR 循环以一个确定的次数执行一个代码块,由计数器变量控制。在 Edexcel 伪代码中,典型语法为 FOR 标识符 ← 起始值 TO 终止值 [STEP 步长]。每次迭代后,计数器按 STEP 值(默认为 1)递增。当计数器超过终止值时循环终止。在循环开始前已知重复次数时,FOR 循环是理想选择,例如处理数组的所有元素。

Negative STEP values allow countdown loops. For example, FOR i ← 10 TO 1 STEP -1 iterates from 10 down to 1. The loop body can contain any valid statements, including nested loops. Candidates commonly use nested FOR loops to traverse 2D arrays: the outer loop controls rows, the inner loop processes columns. This is a recurring theme in A-Level Paper 2 pseudocode questions.

负的 STEP 值允许倒计时循环。例如,FOR i ← 10 TO 1 STEP -1 从 10 向下迭代到 1。循环体可以包含任何有效语句,包括嵌套循环。考生通常使用嵌套 FOR 循环遍历二维数组:外层循环控制行,内层循环处理列。这是 A-Level 试卷二伪代码题目中反复出现的主题。

It is vital to understand the scope of the loop counter. After a FOR loop completes, the counter retains its last value, though in some exam-board pseudocode it may be undefined. Edexcel typically allows the counter to be used after the loop; however, relying on its post-loop value can be error-prone. Explicitly resetting the counter if needed is safer.

理解循环计数器的作用域至关重要。FOR 循环完成后,计数器保留其最后值,尽管在某些考试局的伪代码中它可能未定义。Edexcel 通常允许在循环后使用计数器;然而,依赖其循环后的值容易出错。如有需要,显式重置计数器更为安全。


6. Iteration: WHILE and REPEAT Loops | 迭代:WHILE 与 REPEAT 循环

WHILE and REPEAT loops handle situations where the number of iterations is not known beforehand; they continue until a condition changes. In a WHILE loop, the condition is tested at the beginning. If it is initially false, the loop body never executes. The syntax is WHILE condition DOENDWHILE. This pre-test loop is suitable for reading files until the end or validating user input.

WHILE 和 REPEAT 循环处理事先不知道迭代次数的情况;它们一直执行直到条件发生变化。在 WHILE 循环中,条件在开始时测试。若初始即为假,循环体永不会执行。语法为 WHILE 条件 DOENDWHILE。这种前测试循环适用于读取文件直到末尾或验证用户输入。

A REPEAT…UNTIL loop guarantees at least one execution because the condition is evaluated at the end of the loop body. The Edexcel pseudocode form is REPEATUNTIL condition. This is ideal for menu-driven programs where the user’s choice must be obtained and processed before deciding whether to continue. Carefully choose between WHILE and REPEAT based on whether the loop might need to run zero times.

REPEAT…UNTIL 循环确保至少执行一次,因为条件在循环体末尾求值。Edexcel 伪代码形式为 REPEATUNTIL 条件。这种循环非常适合菜单驱动程序,其中必须获取并处理用户的选择,然后再决定是否继续。根据循环是否需要执行零次,谨慎选择 WHILE 或 REPEAT。

Infinite loops occur when the terminating condition never becomes true. Candidates must ensure that inside the loop body, a variable that influences the condition is updated. For example, incrementing a counter inside a WHILE loop. Exam questions often ask learners to identify or fix infinite loops. A trace table again serves as an indispensable debugging tool for checking loop termination.

当终止条件永远不为真时会发生无限循环。考生必须确保在循环体内部,影响条件的变量得到更新。例如,在 WHILE 循环内递增计数器。试题常要求学习者识别或修复无限循环。跟踪表再次成为检查循环终止不可或缺的调试工具。


7. Subprograms: Procedures and Functions | 子程序:过程与函数

Subprograms enable modularity, code reuse and abstraction. A procedure performs a task but does not return a value (though it can modify variables via parameters). A function always returns a single value of a specified data type. In Edexcel pseudocode, a procedure is declared with PROCEDURE name(parameters) and a function with FUNCTION name(parameters) RETURNS type. Understanding this distinction is frequently examined.

子程序实现了模块化、代码复用和抽象。一个过程执行任务但不返回值(尽管它可以通过参数修改变量)。一个函数总是返回一个指定数据类型的一个值。在 Edexcel 伪代码中,过程用 PROCEDURE 名称(参数) 声明,函数用 FUNCTION 名称(参数) RETURNS 类型 声明。理解这一区别经常成为考查点。

Local variables declared inside a subprogram cannot be accessed outside; this supports encapsulation and prevents unintended side-effects. Global variables, declared in the main program, are accessible everywhere but should be used sparingly because they make code harder to debug and maintain. Edexcel expects candidates to demonstrate appropriate use of local variables in their solutions.

在子程序内部声明的局部变量不能在外部访问;这支持封装并防止意外的副作用。全局变量在主程序中声明,各处皆可访问,但应谨慎使用,因为它们使代码更难调试和维护。Edexcel 期望考生在解决方案中展示对局部变量的恰当使用。

Passing data into and out of subprograms is done via parameters. Formal parameters are listed in the subprogram definition; actual parameters (arguments) are supplied during the call. The number, order and type of arguments must match the formal parameters. Edexcel mark schemes penalise mismatched parameter counts. Parameters promote generality – the same function can process different data sets.

通过参数将数据传递入和传输出子程序。形式参数列在子程序定义中;实际参数(实参)在调用时提供。实参的数量、顺序和类型必须与形式参数匹配。Edexcel 评分方案对参数数量不匹配进行扣分。参数促进了通用性——同一个函数可以处理不同的数据集。


8. Parameter Passing Mechanisms | 参数传递机制

Two fundamental mechanisms exist: pass-by-value and pass-by-reference. In pass-by-value, a copy of the argument is assigned to the parameter; changes inside the subprogram do not affect the original variable. In pass-by-reference, the parameter is an alias for the original variable, so modifications persist after the subprogram ends. Edexcel pseudocode may explicitly indicate this, for example by using BYREF or requiring an ampersand.

存在两种基本机制:按值传递和按引用传递。按值传递时,将实参的一个副本赋给形参;子程序内部的更改不会影响原始变量。按引用传递时,形参是原始变量的别名,因此修改在子程序结束后仍然存在。Edexcel 伪代码可能显式指出这一点,例如通过使用 BYREF 或要求使用和号。

Functions usually employ pass-by-value to avoid side-effects; procedures often use by-reference to return multiple values. A typical question asks: ‘Explain how parameters can be used to return two values from a procedure.’ The answer involves defining two BYREF parameters and updating them inside the procedure. Trainees must know how to declare and call such procedures correctly.

函数通常采用按值传递以避免副作用;过程常使用按引用传递来返回多个值。一道典型题目问:“解释如何利用参数从一个过程返回两个值。”答案涉及定义两个 BYREF 参数并在过程内部更新它们。学员必须知道如何正确声明和调用这类过程。

The choice between mechanisms affects program safety and clarity. Pass-by-value protects data, while pass-by-reference saves memory and enables in-place modification. In languages like Python, mutable objects (lists) are passed by reference by default, which can confuse candidates moving from pseudocode to real code. For the A-Level exam, stick to the Edexcel-specified pseudo notation.

机制的选择影响程序的安全性和清晰度。按值传递保护数据,而按引用传递节省内存并允许就地修改。在 Python 等语言中,可变对象(列表)默认按引用传递,这可能使从伪代码转到真实代码的考生感到困惑。在 A-Level 考试中,应坚持使用 Edexcel 指定的伪代码记法。


9. Recursion Basics | 递归基础

Recursion occurs when a function calls itself to solve a smaller instance of the same problem. Every recursive solution must have a base case – a condition that stops the recursion – and a recursive case that reduces the problem size. The classic example is computing factorials: FUNCTION Factorial(n) RETURNS INTEGER with base case n=0 returning 1, and recursive case returning n * Factorial(n-1).

当一个函数调用自身来解决同一问题的更小实例时,就发生了递归。每个递归解决方案必须有一个基准情形——一个停止递归的条件——和一个递归情形来缩小问题规模。经典示例是计算阶乘:FUNCTION Factorial(n) RETURNS INTEGER,基准情形 n=0 返回 1,递归情形返回 n * Factorial(n-1)。

Recursion can lead to elegant code for problems such as tree traversals or the Towers of Hanoi, but it consumes additional stack memory. Each recursive call places a new frame on the call stack; if the base case is never reached, a stack overflow error occurs. Edexcel often requires candidates to trace a recursive algorithm, showing the sequence of calls and the stack contents.

递归能为树遍历或汉诺塔等问题带来优雅的代码,但它消耗额外的栈内存。每次递归调用都在调用栈上放置一个新的帧;如果永远达不到基准情形,就会发生栈溢出错误。Edexcel 常要求考生跟踪一个递归算法,展示调用序列和栈的内容。

Comparing recursion and iteration is a common exam topic. While recursion is often more intuitive for problems with a naturally recursive structure, iteration tends to be more memory-efficient. Candidates should be able to convert a simple recursive algorithm into an iterative one using a loop, and to explain when recursion is justified – for instance, in quicksort or binary search tree operations.

比较递归与迭代是一个常见的考试主题。虽然对于具有自然递归结构的问题递归通常更直观,但迭代往往更具内存效率。考生应能够使用循环将一个简单的递归算法转换为迭代算法,并解释何时使用递归是合理的——例如,在快速排序或二叉搜索树操作中。


10. Common Programming Errors and Debugging | 常见编程错误与调试

Programming errors fall into three categories: syntax errors, runtime errors and logic errors. Syntax errors, such as missing ENDIF or misspelt keywords, prevent the program from compiling. Runtime errors occur during execution, e.g. division by zero or array index out of bounds. Logic errors produce incorrect output while the program runs without crashing; these are often the hardest to detect.

编程错误分为三类:语法错误、运行时错误和逻辑错误。语法错误,如遗漏 ENDIF 或拼错关键字,使程序无法编译。运行时错误在执行过程中发生,例如除以零或数组索引越界。逻辑错误在不导致崩溃的情况下产生错误输出;这些通常最难检测。

A trace table is the examiner’s preferred debugging tool. It records the line number, variable values and condition outcomes step by step. By filling a trace table for a given algorithm, candidates can identify where actual behaviour diverges from the intended behaviour. Edexcel’s written papers frequently include a trace table exercise worth several marks; neat, systematic completion wins full marks.

跟踪表是考官偏爱的调试工具。它逐步记录行号、变量值和条件结果。通过为给定算法填写跟踪表,考生可以识别实际行为与预期行为的分歧点。Edexcel 的笔试经常包含一道分值可观的跟踪表练习;整齐、系统地完成可以拿到满分。

Good coding habits reduce errors: meaningful variable names, consistent indentation, modular design and adding comments. When debugging, use ‘dry running’ (mental execution) and test boundary values – for example, the first and last iterations of a loop. Understanding the IDE tools available, such as breakpoints and watch windows, is relevant for the practical project but less so for the pseudocode exam.

良好的编码习惯可减少错误:有意义的变量名、一致的缩进、模块化设计和添加注释。调试时,使用“人工走查”(脑中执行)并测试边界值——例如,循环的第一次和最后一次迭代。理解可用的 IDE 工具,如断点和监视窗口,与实践项目相关,但对伪代码考试不太重要。


11. Pseudocode Conventions in Edexcel | Edexcel 伪代码规范

Edexcel provides a definitive pseudocode reference that candidates are expected to adhere to. Key conventions include: assignment with ←, conditional equality with =, input/output keywords INPUT and OUTPUT (or PRINT), comments preceded by //, and block terminators such as ENDIF, ENDWHILE, ENDPROCEDURE. Constants are declared using CONSTANT . All words in bold are reserved words.

Edexcel 提供了一个明确的伪代码参考,要求考生遵守。关键规范包括:用 ← 进行赋值,用 = 表示条件相等,输入/输出关键字 INPUT 和 OUTPUT(或 PRINT),注释以 // 引导,以及块终止符如 ENDIF、ENDWHILE、ENDPROCEDURE。常量使用 CONSTANT <名称> ← <值> 声明。所有粗体单词均为保留字。

Array indexing is zero-based unless stated otherwise

Published by TutorHao | A-Level 编程 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