IGCSE OCR Computer Science: Programming Fundamentals Revision Guide | IGCSE OCR 计算机:编程基础 考点精讲

📚 IGCSE OCR Computer Science: Programming Fundamentals Revision Guide | IGCSE OCR 计算机:编程基础 考点精讲

Mastering the fundamentals of programming is the cornerstone of success in the IGCSE OCR Computer Science specification. This guide systematically breaks down every key topic — from variables and control structures to subprograms and file handling — using OCR’s own Exam Reference Language. Whether you are just starting out or need a focused revision sprint, these bilingual notes will strengthen both your theoretical understanding and your practical coding skills.

掌握编程基础是攻克 IGCSE OCR 计算机科学考纲的基石。本指南系统梳理了从变量、控制结构到子程序和文件处理等一系列核心考点,全部采用 OCR 官方考试参考语言。无论你是初次接触编程,还是需要进行冲刺复习,这些中英双语笔记都将帮助你夯实理论理解,并提升实际编码能力。


1. Variables, Constants and Data Types | 变量、常量与数据类型

In OCR’s Exam Reference Language, you must declare every variable with a specific data type before using it. The five primitive types you will encounter are INTEGER (whole numbers), REAL (decimal numbers), CHAR (a single character), STRING (a sequence of characters) and BOOLEAN (TRUE or FALSE). Use CONSTANT to create a named value that cannot change during execution, which improves code clarity and prevents accidental modification.

在 OCR 考试参考语言中,使用变量前必须用明确的数据类型声明。你需要掌握的五个基本类型是:INTEGER(整数)、REAL(实数/小数)、CHAR(单个字符)、STRING(字符串)以及 BOOLEAN(布尔值,TRUE 或 FALSE)。使用 CONSTANT 可以创建一个在执行中不可更改的命名值,这既能提高代码清晰度,也能防止意外修改。

The assignment operator is a left-pointing arrow . For example, score ← 0 stores the integer 0 in the variable score. You can also assign an expression, such as area ← length * width. Always check that the right-hand side evaluates to a type compatible with the variable’s declared type; attempting to assign a STRING to an INTEGER variable will cause a run-time error.

赋值运算符是一个左向箭头 。例如 score ← 0 将整数 0 存入变量 score。你也可以赋值一个表达式,如 area ← length * width。务必确保等号右边的求值结果与变量的声明类型兼容;试图将一个 STRING 赋给 INTEGER 变量会引发运行时错误。

Constants follow a similar declaration style: CONSTANT VATRATE ← 0.2. They are especially useful for storing values that appear multiple times, such as tax rates or mathematical constants like π. Even though OCR does not require a separate CONST keyword, using CONSTANT clearly signals your intent to the examiner and helps you write maintainable code.

常量遵循类似的声明方式:CONSTANT VATRATE ← 0.2。当同一个数值在代码中出现多次(如税率或 π 等数学常数)时,用常量格外方便。虽然 OCR 不要求单独的 CONST 关键字,但使用 CONSTANT 能向考官清晰传达你的意图,并助你写出易于维护的代码。


2. Input, Output and Type Conversions | 输入、输出与类型转换

Interaction with the user is handled by two straightforward commands: OUTPUT to display information on the screen and INPUT to read data typed by the user. For example, OUTPUT "Enter your age:" prints the message, and INPUT age stores the entered value into the variable age. The variable must already have been declared with the correct type.

与用户的交互通过两个简洁的命令完成:OUTPUT 用于在屏幕上显示信息,INPUT 用于读取用户键入的数据。例如 OUTPUT "Enter your age:" 输出提示信息,然后 INPUT age 将用户输入的值存入变量 age。该变量必须事先以正确的类型声明好。

When receiving numerical input, the user types digits, but the program might treat it as a string unless a conversion function is applied. OCR provides STRING_TO_INT to convert a string into an integer and STRING_TO_REAL for real numbers. Similarly, you can transform a number into a human-friendly string with INT_TO_STRING and REAL_TO_STRING. These functions are crucial when you need to concatenate numbers with text for display.

接收数值输入时,用户键入的是数字字符,但程序可能将其视作字符串,除非使用转换函数。OCR 提供了 STRING_TO_INT 将字符串转为整数,以及 STRING_TO_REAL 转为实数。类似地,你也可以用 INT_TO_STRINGREAL_TO_STRING 将数字转成便于阅读的字符串。当需要将数字和文字拼接显示时,这些函数至关重要。

A typical pattern is: OUTPUT "Enter a number:", INPUT userEntry (declared as STRING), num ← STRING_TO_INT(userEntry). This guarantees that num now holds an INTEGER ready for arithmetic. Always guard against invalid conversions in your algorithms by checking the input format if the question asks for robust design.

一个典型模式是:OUTPUT "Enter a number:"INPUT userEntry(声明为 STRING),num ← STRING_TO_INT(userEntry)。这就确保了 num 现在持有一个可用于运算的整数。如果题目要求设计健壮的方案,记得在算法中检查输入格式,以防止非法转换。


3. Sequence, Selection and Iteration | 顺序、选择与迭代

Every program is built from three fundamental control structures: sequence (one statement after another), selection (decision-making with IF statements) and iteration (looping with FOR or WHILE). In the exam, you must read, trace and write algorithms that combine all three. Understanding how they nest inside one another is essential for solving multi-step problems.

任何一个程序都由三种基本控制结构组成:顺序(语句逐条执行)、选择(用 IF 语句做决策)以及迭代(用 FOR 或 WHILE 循环)。在考试中,你必须能阅读、追踪并编写组合运用这三种结构的算法。理解它们如何相互嵌套是解决多步骤问题的关键。

Sequence is the default: instructions run in the order they appear. There is no special keyword; just write the statements one line after another. However, you must ensure that a variable is declared and given a value before it is used in a calculation or output — a common mistake is to place OUTPUT x before x ← 5.

顺序是默认行为:指令依照出现的先后次序执行。无需特殊关键字;只需将语句一行一行写下即可。但你务必保证变量在使用之前已被声明并赋值——一个常见的错误是把 OUTPUT x 放在 x ← 5 之前。

Selection is dominated by the IF ... THEN ... ELSE ... ENDIF structure. You can also extend it with ELSE IF for multiple branches. OCR expects you to use comparison operators (=, <>, >, <, >=, <=) and logical operators (AND, OR, NOT) inside conditions. Indentation is not strictly marked but makes your pseudo-code clearer.

选择结构主要由 IF ... THEN ... ELSE ... ENDIF 组成。你也可以通过 ELSE IF 扩展出多条分支。OCR 考察你在条件中使用比较运算符(=<>><>=<=)和逻辑运算符(ANDORNOT)的能力。缩进虽然不直接评分,但能使你的伪代码更加清晰。

Iteration comes in two flavours: count-controlled loops (FOR ... NEXT) and condition-controlled loops (WHILE ... ENDWHILE). Use a FOR loop when the number of repetitions is known in advance, e.g. stepping through the indices of an array. Use a WHILE loop when you must repeat an unknown number of times until a condition becomes false, such as prompting a user until a valid password is entered.

迭代有两种形式:计数控制的循环(FOR ... NEXT)和条件控制的循环(WHILE ... ENDWHILE)。当重复次数事先已知(例如遍历数组的下标)时,使用 FOR 循环。当需要重复未知次数、直到某个条件变为假时才停止时(例如反复提示用户直到输入有效密码),则使用 WHILE 循环。


4. Decision Making with IF Statements | 用 IF 语句进行决策

The basic decision block is written as:

基本的决策块写法如下:

IF condition THEN
    // statements
ENDIF

To add an alternative path, insert ELSE: IF score >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF. For multiple, mutually exclusive conditions, chain ELSE IF branches. Remember that only the first true branch executes; the rest are skipped. This is extremely useful for grading systems or menu selections.

若要添加备选路径,插入 ELSEIF score >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF。对于多个、互斥的条件,可串联 ELSE IF 分支。记住,只有第一个为真的分支会执行;其余分支会被跳过。这对于设计评分系统或菜单选择非常有用。

Nested IF statements allow fine-grained decisions but can become messy. When nesting, line up ENDIF with its corresponding IF and use indentation consistently. An alternative for multi-value checks is a CASE statement (also called SWITCH in some languages). OCR supports SELECT ... FROM ... CASE ... ENDSELECT, which compares a variable against several constant values and is easier to read than a long chain of ELSE IFs.

嵌套的 IF 语句能实现精细的判断,但可能变得混乱。嵌套时,应令 ENDIF 与其对应的 IF 对齐,并保持一致的缩进。对于多值检查,另一种选择是 CASE 语句(某些语言中称 SWITCH)。OCR 支持 SELECT ... FROM ... CASE ... ENDSELECT,它将一个变量与多个常量值进行比较,比一长串 ELSE IF 更易读。

When writing conditions, use brackets to avoid ambiguity, even if OCR does not enforce them. For example, write IF (age >= 18) AND (member = TRUE) THEN. Also remember De Morgan’s laws when negating combined conditions: NOT (A AND B) is equivalent to (NOT A) OR (NOT B). This logical thinking is often tested in trace-table questions.

编写条件时,建议使用括号以避免歧义,即使 OCR 不强制要求。例如写成 IF (age >= 18) AND (member = TRUE) THEN。同时要记住,在否定复合条件时的德摩根律:NOT (A AND B) 等价于 (NOT A) OR (NOT B)。这种逻辑思维常常在追踪表演题中考查。


5. Looping with FOR and WHILE | FOR 与 WHILE 循环

The definite loop in OCR is written as:

OCR 中的计数确定循环写法如下:

FOR index ← 1 TO 10
    OUTPUT index
NEXT index

The loop variable index automatically takes values 1, 2, …, 10. You can also specify a STEP value to change the increment; for example, FOR count ← 10 TO 0 STEP -1 counts downwards. Using FOR makes your algorithm tidy when processing each element of an array or printing a multiplication table.

循环变量 index 会自动取值 1, 2, …, 10。你还可以通过 STEP 指定步长来改变增量;例如 FOR count ← 10 TO 0 STEP -1 会倒计数。当需要处理数组的每个元素或打印乘法表时,使用 FOR 能让你的算法整洁明了。

The indefinite loop is:

条件不确定循环写法如下:

WHILE password <> "secret"
    OUTPUT "Try again"
    INPUT password
ENDWHILE

This repeats as long as the condition is true. If the condition is false at the very start, the loop body is skipped entirely. A common exam pitfall is an infinite loop caused by forgetting to update the condition inside the body, such as never reading a new password. Always ensure the loop is making progress towards termination.

该循环在条件为真时不断重复。如果一开始条件就为假,循环体将被完全跳过。一个常见的考试陷阱是忘记在循环体内更新条件,从而导致无限循环,例如从不读取新的 password。务必确保循环正在朝终止的方向前进。

Nested loops are powerful: putting a FOR loop inside another FOR lets you work with two-dimensional data like a grid. For instance, to print a 5×5 grid of stars, nest two FOR loops, one for rows and one for columns. Trace tables for nested loops can look intimidating, but carefully tracking each variable step by step always wins the marks.

嵌套循环威力强大:在一个 FOR 循环内再放一个 FOR,便可处理如网格这样的二维数据。例如,要打印一个 5×5 的星号矩阵,可嵌套两个 FOR 循环,一个控制行,一个控制列。嵌套循环的追踪表可能看起来吓人,但只要你逐步仔细记录每个变量,就一定能拿到分数。


6. String Manipulation and Common Operations | 字符串操作与常见运算

Strings in OCR can be manipulated using several built-in functions and operators. You can join two strings (concatenation) with the & operator, for instance fullName ← firstName & " " & surname. Do not be tempted to use + — in OCR’s reference language, + is strictly for arithmetic and will not work on strings.

OCR 中的字符串可通过多个内置函数和运算符进行处理。你可以用 & 运算符拼接两个字符串,例如 fullName ← firstName & " " & surname。不要试图使用 + ——在 OCR 参考语言中,+ 严格用于算术运算,不能用于字符串。

Key functions to memorise are:

需要牢记的关键函数包括:

  • LENGTH(str) — returns the number of characters.
  • SUBSTRING(str, start, length) — extracts a portion of the string; positions usually start at 1.
  • POSITION(str, searchChar) — finds the position of a character or substring, returning 0 if not found.
  • LENGTH(str) — 返回字符个数。
  • SUBSTRING(str, start, length) — 提取字符串的一部分;位置通常从 1 开始。
  • POSITION(str, searchChar) — 查找字符或子串的位置,若未找到则返回 0。

Converting between CHAR and its ASCII code is also required: CHAR_TO_CODE('A') gives 65, and CODE_TO_CHAR(66) yields ‘B’. This is useful for tasks like shifting characters in a Caesar cipher. When you encounter a question asking you to validate an input format, think in terms of cycling through each character and using these functions to check properties.

字符与 ASCII 码之间的转换也需要掌握:CHAR_TO_CODE('A') 得到 65,CODE_TO_CHAR(66) 则产生 ‘B’。这在实现凯撒密码等字母移位任务时很有用。当你碰到要求验证输入格式的题目时,可以设想逐个字符循环,并用这些函数检查字符的属性。

String comparison uses standard relational operators, but be aware that uppercase letters come before lowercase letters in ASCII order, so "Z" < "a" is true. When sorting lexicographically, you might need to convert all characters to the same case using loops and ASCII arithmetic.

字符串比较可用标准关系运算符,但需注意:在 ASCII 顺序中,大写字母排在小写字母之前,因此 "Z" < "a" 为真。在按字典序排序时,你可能需要通过循环和 ASCII 算术将所有字符转换为同一大小写。


7. Arrays (Lists) and Their Applications | 数组(列表)及其应用

An array in OCR is a collection of elements, all of the same data type, accessed by a numeric index. You must explicitly declare the size and type: ARRAY numbers[5] OF INTEGER creates space for five integers. Elements are assigned with numbers[1] ← 42. Indices typically start at 1, but the question will specify; some problems start at 0, so read carefully.

OCR 中的数组是一组相同数据类型的元素集合,通过数字下标访问。你必须显式声明大小和类型:ARRAY numbers[5] OF INTEGER 为五个整数分配空间。元素的赋值如 numbers[1] ← 42。下标通常从 1 开始,但题目会说明;有些问题从 0 开始,请仔细读题。

Traversing an array is most naturally done with a FOR loop: FOR i ← 1 TO 5 ... numbers[i] ... NEXT i. Common algorithms include finding the maximum value, calculating the average, and linear search. For linear search, you iterate through the array and compare each element to the target; if found, you can output its index or set a Boolean flag.

遍历数组最自然地使用 FOR 循环:FOR i ← 1 TO 5 ... numbers[i] ... NEXT i。常见算法包括查找最大值、计算平均值和线性搜索。对于线性搜索,你需要遍历数组并将每个元素与目标值比较;如果找到,可以输出其下标或设置布尔标志。

Two-dimensional arrays are declared like ARRAY grid[3][4] OF INTEGER and accessed with grid[row][col]. They are ideal for representing boards in games or spreadsheets. When asked to write an algorithm that processes a 2D array, nest two FOR loops: the outer loop for rows and the inner for columns.

二维数组声明如 ARRAY grid[3][4] OF INTEGER,访问时用 grid[row][col]。它们非常适合表示游戏棋盘或电子表格。如果被要求编写处理二维数组的算法,就嵌套两个 FOR 循环:外层循环控制行,内层控制列。

Keep in mind that OCR does not support dynamic arrays that resize automatically. If the problem asks you to store an unknown amount of data, you will usually be told the maximum possible size, and you should declare the array with that upper bound and use a counter to track how many elements are actually stored.

请记住,OCR 不支持能自动调整大小的动态数组。如果题目要求存储数量未知的数据,通常会给出最大可能的大小;你应当以这个上限声明数组,并额外用一个计数器跟踪实际存储的元素数量。


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

Modular code is written using subprograms. A function takes parameters, performs a task and returns exactly one value. A procedure can also take parameters, but it does not return a value; it simply executes a sequence of statements and may affect the program state via output or by modifying arguments passed by reference. OCR marks clearly distinguish between the two.

模块化代码通过子程序来编写。函数接收参数,执行任务并返回恰好一个值。过程也可以接收参数,但它不返回数值;它只是执行一系列语句,可通过输出或通过引用传递修改参数来影响程序状态。OCR 评分会严格区分两者。

A function is declared as:

函数的声明方式为:

FUNCTION add(a,b: INTEGER) RETURNS INTEGER
    RETURN a + b
ENDFUNCTION

Call it with sum ← add(3,5). The RETURNS keyword specifies the data type of the answer. Inside the function, you must use RETURN to send back a value. A procedure, on the other hand, starts with PROCEDURE greet(name: STRING) and ends with ENDPROCEDURE; it is invoked simply with greet("Alice").

调用方式为 sum ← add(3,5)RETURNS 关键字指定了返回值的数据类型。在函数内部,必须使用 RETURN 语句返回一个值。而过程则不同,它从 PROCEDURE greet(name: STRING) 开始,以 ENDPROCEDURE 结束;只需 greet("Alice") 即可调用。

Parameters can be passed by value (default) or by reference. When passing by reference, changes to the parameter inside the subprogram affect the original variable. The exam may ask you to predict the output of code that mixes value and reference parameters, so trace carefully: a variable passed by value will remain unchanged in the calling part.

参数可以按值传递(默认)或按引用传递。按引用传递时,子程序内对参数的修改会影响原始变量。考试可能会要求你预测混合了值和引用参数的代码的输出,因此请仔细追踪:按值传递的变量在调用部分将保持不变。

Well-named subprograms are self-documenting and reduce repetition. In the 6-mark algorithm design questions, using appropriate procedures and functions demonstrates high-level problem-solving and often pushes the answer into the top band.

命名良好的子程序具有自文档化特性,并能减少重复。在 6 分的算法设计题中,合理使用过程和函数能体现高层次的解题思维,往往能使答案进入高分段。


9. File Handling and Persistent Storage | 文件处理与持久化存储

Programs often need to read data from a text file or write results to one. OCR’s file commands are straightforward: you open a file for reading or writing, perform operations, then close it. The syntax for reading is READFILE "data.txt", line, which reads the next line into a STRING variable. To process every line, wrap it in a WHILE NOT EOF("data.txt") loop.

程序经常需要从文本文件中读取数据,或将结果写入文件。OCR 的文件命令简单明了:打开文件进行读取或写入,执行操作,然后关闭。读取的语法为 READFILE "data.txt", line,它将下一行读入一个 STRING 变量。若要处理每一行,可将其包裹在 WHILE NOT EOF("data.txt") 循环中。

Writing to a file uses WRITEFILE "output.txt", data. This can write a single line; to write multiple lines, call the command repeatedly inside a loop. Be aware that writing to an existing file will typically overwrite its contents. If you need to append data, the question will usually provide a specific command; otherwise, assume overwriting.

写入文件使用 WRITEFILE "output.txt", data。它能写入一行;若要写入多行,在循环内重复调用该命令即可。请注意,写入已存在的文件通常会覆盖原有内容。如果题目要求追加数据,通常会给出特定命令;否则默认覆盖。

Before reading, you often need to split a line into fields, using the function SPLIT(line, ',') which returns an array of substrings. For example, a CSV line “Alice, 15, B” can be split into three elements for further processing. Combining file handling with arrays and string manipulation is a common longer question on the written paper.

在读取之后,经常需要将一行拆分成字段,可使用 SPLIT(line, ',') 函数,它返回一个子串数组。例如,CSV 行 “Alice, 15, B” 可以拆分为三个元素以供后续处理。将文件操作、数组与字符串处理结合起来,是笔试中常见的长题目。

Always remember to close the file after use, even if the exam’s pseudo-code may omit it for brevity. In your own algorithms, a comment like // close the file shows awareness of good practice. And never hard-code absolute file paths like "C:\data.txt"; use simple filenames as specified in the question.

每次使用后,务记关闭文件,即使考试伪代码为简洁可能省略。在你自己的算法中,加上一句 // close the file 注释便展现出良好的实践意识。并且,永远不要硬编码绝对路径如 "C:\data.txt";一律使用题目指定的简单文件名。


10. Basic Algorithms in OCR Context | OCR 语境下的基础算法

Several standard algorithms appear repeatedly. A linear search examines each element of an array in order until a match is found or the end is reached. Its pseudo-code uses a WHILE loop (or a FOR loop with an early exit). Remember to initialise a Boolean variable like found ← FALSE and set it to TRUE when the target is located.

有几个标准算法反复出现。线性搜索逐个检查数组元素,直到找到匹配项或到达末尾。其伪代码使用 WHILE 循环(或带提前退出的 FOR 循环)。记得初始化一个布尔变量如 found ← FALSE,并在找到目标时将其设为 TRUE

Counting occurrences is a simple variation: initialise a counter cnt ← 0, loop through the array, and increment cnt every time an element meets the condition. Similarly, finding the maximum starts by assuming the first element is the largest (maxVal ← arr[1]) and then, for each subsequent element, if it is greater, update maxVal.

统计出现次数是一个简单变体:初始化计数器 cnt ← 0,遍历数组,每当元素满足条件时就将 cnt 增 1。同理,求最大值开始时假设第一个元素最大(maxVal ← arr[1]),然后对于每个后续元素,若其更大则更新 maxVal

Bubble sort is the only sorting algorithm explicitly mentioned in the OCR specification. It works by repeatedly passing through the array, comparing adjacent elements and swapping them if they are in the wrong order. You must be able to dry-run a bubble sort on a small array, showing the array after each pass, and identify when the array is sorted.

冒泡排序是 OCR 考纲中唯一明确提及的排序算法。它通过反复遍历数组、比较相邻元素并在顺序错误时交换它们来工作。你必须能够对一个小型数组执行冒泡排序的干燥运行(dry-run),展示每一轮后的数组状态,并辨认出何时数组已完成排序。

Advanced algorithms like binary search are not required in the IGCSE, but you may need to combine the basic ones creatively. For example, a question might ask you to design an algorithm that reads names from a file, stores them in an array, sorts them, and then allows a user to search for a name. Breaking such a problem into subprograms (one for reading, one for sorting, one for searching) is the key to exam success.

像二分搜索这类高级算法在 IGCSE 阶段不作要求,但你可能需要创造性地组合基础算法。例如,一道题目可能要求你设计一个算法:从文件读取名字,存入数组,排序,然后允许用户搜索某个名字。将此类问题拆解为子程序(一个负责读取,一个负责排序,一个负责搜索)是考试成功的关键。


11. Random Numbers and Basic Arithmetic Operations | 随机数与基本算术运算

Generating unpredictable values is useful for simulations and games. OCR provides RANDOM_INT(min, max) which returns an integer between min and max inclusive. For example, to simulate a dice roll, call dice ← RANDOM_INT(1,6). Remember that every run of the program may produce different sequences unless a seed is specified; the exam will not ask about seeding, just the function’s range.

生成不可预测的数值在模拟和游戏中很有用。OCR 提供了 RANDOM_INT(min, max),它返回一个介于 minPublished by TutorHao | IGCSE 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