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

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

Programming fundamentals form the bedrock of all software development and computer science problem-solving. In both IB and WJEC specifications, a clear grasp of data types, control structures, algorithms, and modular programming is essential for success. This guide unpacks each core concept, providing bilingual explanations so that you can reinforce your understanding whether you think in English or Chinese. We will explore everything from variables and conditionals to arrays and recursion, ensuring that you are fully prepared for exam-style coding questions and theoretical essays.

编程基础是所有软件开发和计算机科学问题解决的基石。在 IB 和 WJEC 考试大纲中,清晰掌握数据类型、控制结构、算法和模块化编程是成功的关键。本指南拆解每个核心概念,提供中英双语解释,以便无论你用英语还是中文思考,都能加深理解。我们将从变量和条件语句到数组和递归逐一探讨,确保你为考试风格的编程题和理论简答题做好充分准备。

1. Data Types and Variables | 数据类型与变量

Data types tell the compiler or interpreter how much memory to allocate and what operations can be performed. The most common primitive types include integer, float (real), Boolean, and character. In many languages, such as Python, Java, or C#, you must either explicitly declare the type or rely on dynamic typing. For example, an integer variable age might be declared as int age = 17; in Java, or simply age = 17 in Python. Choosing the correct type avoids overflow errors and promotes efficient memory usage.

数据类型告诉编译器或解释器需要分配多少内存,以及可以执行哪些操作。最常见的基本类型包括整数、浮点数(实数)、布尔值和字符。在许多语言中,比如 Python、Java 或 C#,你必须显式声明类型或依赖动态类型。例如,整型变量 age 在 Java 中可能声明为 int age = 17;,而在 Python 中只需写 age = 17。选择正确的类型可以避免溢出错误,并提高内存使用效率。

Variables are named storage locations whose values can change during execution. Each variable follows scope rules: local variables exist only within a function, while global variables are accessible throughout the program. Good naming conventions (e.g., camelCase or snake_case) improve code readability. Constants, declared with final in Java or const in others, hold values that must not change, protecting critical data such as the mathematical constant π (3.14159) or the maximum score in a game.

变量是命名的存储位置,其值在程序执行过程中可以改变。每个变量遵循作用域规则:局部变量仅存在于函数内部,而全局变量在整个程序中可访问。良好的命名约定(例如驼峰式或下划线式)能提高代码可读性。常量在 Java 中用 final 或在其他语言中用 const 声明,存放不可更改的值,从而保护关键数据,如数学常数 π(3.14159)或游戏中的最高分。


2. Operators and Expressions | 运算符与表达式

Operators combine values and variables to produce new values. Arithmetic operators (+, -, *, /, %) perform calculations. The modulus operator (%) gives the remainder; for instance, 10 % 3 evaluates to 1. Assignment operators (=, +=, -=) store or update values. Comparison operators (==, !=, <, >, <=, >=) return Boolean results, essential for building conditions. Logical operators (AND, OR, NOT) link multiple Boolean expressions. In IB pseudocode, && or AND may be used for conjunction.

运算符将值和变量组合起来产生新值。算术运算符(+、-、*、/、%)执行计算。取模运算符(%)给出余数;例如,10 % 3 的结果为 1。赋值运算符(=、+=、-=)存储或更新值。比较运算符(==、!=、<、>、<=、>=)返回布尔结果,是构建条件的基础。逻辑运算符(AND、OR、NOT)连接多个布尔表达式。在 IB 伪代码中,可能使用 &&AND 表示逻辑与。

Operator precedence determines the order of evaluation: parentheses first, then arithmetic operators, then comparisons, and finally logical operators. For example, in the expression 2 + 3 * 4, multiplication occurs before addition, giving 14. Using brackets clarifies intention: (2 + 3) * 4 = 20. Misunderstanding precedence is a common source of runtime bugs, so always check complex expressions.

运算符优先级决定了求值顺序:括号最优先,然后是算术运算符,再是比较运算符,最后是逻辑运算符。例如,在表达式 2 + 3 * 4 中,乘法先于加法,得到 14。使用括号可以明确意图:(2 + 3) * 4 = 20。误解优先级是运行时错误的常见来源,因此务必检查复杂表达式。


3. Input and Output | 输入与输出

Programs interact with users through input and output (I/O). In console-based programs, input functions read text entered by the user, while output functions display results on the screen. Common constructs include input() in Python, Scanner in Java, and Console.ReadLine() in C#. When reading input, it is often necessary to convert the string data into the desired type – for example, int(input(‘Enter age: ‘)) in Python or Integer.parseInt() in Java. Formatting output with placeholders, such as printf or f-strings, makes data presentation clearer.

程序通过输入和输出(I/O)与用户交互。在控制台程序中,输入函数读取用户输入的文本,而输出函数将结果显示在屏幕上。常见结构包括 Python 中的 input()、Java 中的 Scanner 以及 C# 中的 Console.ReadLine()。读取输入时,通常需要将字符串数据转换为所需类型——例如 Python 中的 int(input(‘输入年龄: ‘)) 或 Java 中的 Integer.parseInt()。使用占位符(如 printf 或 f-string)格式化输出可使数据呈现更清晰。

In WJEC-style algorithmic questions, the keywords INPUT and OUTPUT are used. For instance, INPUT name reads a string, while OUTPUT ‘Hello ‘ + name prints a greeting. Files also count as I/O; reading from a text file line by line and writing results to another file is a standard task examined in both IB and WJEC papers. Error handling should accompany file operations to manage missing files gracefully.

在 WJEC 风格的算法题中,使用关键字 INPUTOUTPUT。例如,INPUT name 读取一个字符串,而 OUTPUT ‘Hello ‘ + name 打印问候语。文件也属于 I/O;逐行读取文本文件并将结果写入另一个文件是 IB 和 WJEC 试卷中都会考察的标准任务。文件操作应配有错误处理,以便妥善应对文件缺失的情况。


4. Selection: If-Else and Switch | 选择结构:If-Else 与 Switch

Selection statements allow a program to execute different code paths based on conditions. The if statement evaluates a Boolean expression; if true, the block is executed. if-else provides an alternative path when the condition is false. else if chains test multiple conditions in sequence until one is satisfied. Nesting if statements is possible but can reduce readability; exam questions often ask for equivalent switch-case constructs to improve clarity.

选择语句允许程序根据条件执行不同的代码路径。if 语句求值一个布尔表达式;如果为真,则执行代码块。if-else 在条件为假时提供替代路径。else if 链按顺序测试多个条件,直到其中一个成立。嵌套 if 语句是可行的,但会降低可读性;考试题经常要求写出等效的 switch-case 结构以提高清晰度。

The switch (or case) statement is ideal for comparing a single variable against several constant values. In pseudocode, CASEWHERE or SWITCH may be used. A break statement exits the switch after a match; without it, execution “falls through” to the next case, which is a common pitfall. For IB exams, you must understand the logic of selection and be able to trace algorithm outputs given varying inputs.

switch(或 case)语句非常适合将单个变量与多个常数值进行比较。在伪代码中,可能会使用 CASEWHERESWITCH。匹配后,break 语句退出 switch;如果没有 break,执行会“贯穿”到下一个 case,这是一个常见的陷阱。对于 IB 考试,你必须理解选择的逻辑,并能够根据不同的输入追踪算法输出。


5. Iteration: For and While Loops | 循环结构:For 与 While 循环

Loops repeat a block of code while a condition holds, or for a set number of iterations. While loops check the condition before each iteration, meaning the loop body may never execute if the condition is initially false. Do-while loops (or REPEAT-UNTIL in some pseudocode) guarantee at least one execution. For loops are used when the number of iterations is known, typically incorporating a counter that initialises, checks a condition, and updates each time.

循环在条件成立时或按固定次数重复执行代码块。while 循环在每次迭代前检查条件,这意味着如果条件初始为假,循环体可能一次都不执行。do-while 循环(或某些伪代码中的 REPEAT-UNTIL)保证至少执行一次。for 循环用于迭代次数已知的情况,通常包含一个计数器,每次进行初始化、条件检查和更新。

Loop control variables must be carefully managed to avoid infinite loops. A common mistake is forgetting to increment the counter in a while loop, causing the condition to remain true forever. Nesting loops is powerful for multi-dimensional data, such as printing a multiplication table using an outer loop for rows and an inner loop for columns. IB algorithms often involve iterating through arrays or files, so mastering loop counters and termination conditions is critical.

必须小心管理循环控制变量,以避免无限循环。常见错误是忘记在 while 循环中递增计数器,导致条件永远为真。嵌套循环对处理多维数据非常强大,例如用外层循环控制行、内层循环控制列来打印乘法表。IB 算法经常涉及遍历数组或文件,因此掌握循环计数器和终止条件至关重要。


6. Arrays and Lists | 数组与列表

An array is a data structure that stores a fixed number of elements of the same type in contiguous memory locations. In most languages, arrays are zero-indexed, meaning the first element is at index 0. Arrays can be one-dimensional (a simple list) or multi-dimensional (like a grid or matrix). Declaring an integer array of size 5 in Java: int[] scores = new int[5];. Accessing an element: scores[2] refers to the third element.

数组是一种数据结构,它将固定数量的同类型元素存储在连续的内存位置中。在大多数语言中,数组索引从零开始,即第一个元素的索引为 0。数组可以是一维的(简单列表)或多维的(如网格或矩阵)。用 Java 声明一个大小为 5 的整数数组:int[] scores = new int[5];。访问元素:scores[2] 表示第三个元素。

Dynamic structures like List in Python or ArrayList in Java can grow and shrink in size, offering flexibility. Common operations include traversing elements with a loop, searching for a value, inserting at a specific position, and deleting. In algorithm tracing, you must track the state of an array after each iteration. Sorting algorithms such as bubble sort or selection sort directly manipulate array elements by comparing and swapping adjacent values.

动态结构如 Python 中的 list 或 Java 中的 ArrayList 可以动态增长和缩小,提供了灵活性。常见操作包括使用循环遍历元素、搜索特定值、在指定位置插入以及删除。在进行算法追踪时,你必须跟踪每次迭代后数组的状态。排序算法(如冒泡排序或选择排序)通过比较和交换相邻值直接操作数组元素。


7. Functions and Procedures | 函数与过程

Functions and procedures encapsulate reusable blocks of code, reducing duplication and enhancing maintainability. A function returns a value, while a procedure performs an action without returning a value. In pseudocode, a function definition includes the name, parameters, and return type. Parameters can be passed by value (a copy is made) or by reference (the original variable can be modified). Understanding the difference is a key learning outcome for both IB and WJEC.

函数和过程封装了可复用的代码块,减少重复并提高可维护性。函数返回一个值,而过程执行操作但不返回值。在伪代码中,函数定义包括名称、参数和返回类型。参数可以按值传递(创建副本)或按引用传递(可以修改原始变量)。理解二者的区别是 IB 和 WJEC 的重要学习成果。

Local and global scope applies: variables declared inside a function are local unless specified otherwise. Recursive functions—ones that call themselves—are an elegant solution for problems like factorial calculation or Fibonacci sequence generation, but they must have a base case to prevent infinite recursion. IB exams often feature trace tables that require you to follow the flow of execution through multiple function calls, tracking parameter and return values.

局部和全局作用域也适用:除非特别声明,函数内部声明的变量是局部的。递归函数——即调用自身的函数——对于阶乘计算或斐波那契数列生成等问题是优雅的解决方案,但必须有一个基准情形以防止无限递归。IB 考试中经常出现跟踪表,要求你跟踪通过多次函数调用的执行流程,追踪参数和返回值。


8. String Manipulation | 字符串操作

Strings are sequences of characters, often implemented as arrays of characters. Common operations include concatenation (joining strings), length finding, substring extraction, and character indexing. In pseudocode and high-level languages, built-in functions like length(str), substring(str, start, end), mid(), left(), and right() are used. String comparison can be case-sensitive, so converting to upper or lower case is necessary for case-insensitive matching.

字符串是字符序列,通常实现为字符数组。常见操作包括拼接(连接字符串)、求长度、提取子串和字符索引。在伪代码和高级语言中,会使用内置函数,如 length(str)substring(str, start, end)mid()left()right()。字符串比较可能区分大小写,因此需要转换为大写或小写以实现不区分大小写的匹配。

Parsing and formatting strings is vital for processing user input. For example, converting a comma-separated list into an array or extracting numbers from a string using character-by-character validation. In WJEC algorithmic questions, you may be asked to write pseudocode that counts vowels, reverses a string, or checks for palindromes. These tasks test your ability to use loops and conditional logic to process character data efficiently.

解析和格式化字符串对于处理用户输入至关重要。例如,将逗号分隔的列表转换为数组,或通过逐字符验证从字符串中提取数字。在 WJEC 算法题中,你可能需要编写伪代码来统计元音字母、反转字符串或检查回文。这些任务测试你使用循环和条件逻辑高效处理字符数据的能力。


9. Basic Algorithms: Searching and Sorting | 基本算法:搜索与排序

Searching algorithms locate a target value within a data structure. Linear search checks each element one by one until the target is found or the list ends; it works on unsorted data but has O(n) complexity. Binary search works on sorted arrays by repeatedly dividing the search interval in half, offering O(log n) performance. Understanding preconditions (like a sorted list) and postconditions is essential for full marks in algorithm design questions.

搜索算法在数据结构中定位目标值。线性搜索逐个检查元素,直到找到目标或列表结束;它适用于未排序数据,但复杂度为 O(n)。二分搜索适用于已排序数组,通过反复将搜索区间减半实现 O(log n) 的性能。理解前置条件(如有序列表)和后置条件是算法设计题中取得满分的关键。

Sorting algorithms arrange elements in a specific order, often ascending or descending. Bubble sort repeatedly swaps adjacent elements if they are in the wrong order, passing through the list multiple times until no swaps are needed. Selection sort finds the minimum element and places it at the beginning, continuing for the remaining unsorted portion. Insertion sort builds the sorted array one element at a time by inserting each new item into its correct position. The IB expects students to trace these algorithms step by step and recognise their complexity.

排序算法将元素按特定顺序排列,通常是升序或降序。冒泡排序如果相邻元素顺序错误则反复交换,多次遍历列表直到不再需要交换。选择排序找到最小元素并将其放在开头,接着处理剩余未排序部分。插入排序通过将每个新项插入到正确位置,一次构建一个已排序元素。IB 要求考生逐步跟踪这些算法并认识其复杂度。


10. Debugging and Error Types | 调试与错误类型

Errors in programming fall into three categories: syntax errors, runtime errors, and logic errors. Syntax errors occur when code violates language rules, preventing compilation or interpretation. Runtime errors happen during execution, such as division by zero or null pointer access. Logic errors produce incorrect results without crashing; they are often the hardest to find. Testing with boundary, normal, and abnormal data helps uncover these faults.

编程中的错误分为三类:语法错误、运行时错误和逻辑错误。语法错误发生在代码违反语言规则时,阻止编译或解释。运行时错误在执行期间发生,例如除零或空指针访问。逻辑错误产生错误结果但不崩溃;它们通常最难发现。使用边界数据、正常数据和异常数据进行测试有助于发现这些故障。

Debugging techniques include using print statements to display variable states, stepping through code with a debugger, and constructing trace tables. Trace tables manually track variable values line by line, revealing how data changes over time. For IB, you must be able to complete a trace table given an algorithm, identifying the exact point where a logic error deviates from the expected output. Use of breakpoints and watch expressions in an IDE becomes second nature with practice.

调试技术包括使用打印语句显示变量状态、用调试器逐步运行代码以及构建跟踪表。跟踪表逐行手动记录变量值,揭示数据如何随时间变化。对于 IB,你必须能够根据给定算法填写跟踪表,确定逻辑错误与预期输出偏离的确切位置。在 IDE 中使用断点和监视表达式经过练习将成为第二本能。


11. File Handling | 文件操作

File handling enables persistent storage of data beyond program execution. A file must first be opened in the appropriate mode: read (r), write (w), or append (a). After processing, the file must be closed to release resources. In pseudocode, OPENFILE and CLOSEFILE are used, with a read loop like READFILE or ENDFILE() to detect the end of data. Text files store human-readable characters, while binary files store data in raw byte form.

文件操作允许在程序执行之外持久存储数据。文件必须首先以适当模式打开:读取 (r)、写入 (w) 或追加 (a)。处理完成后,必须关闭文件以释放资源。在伪代码中,使用 OPENFILECLOSEFILE,以及读取循环如 READFILE 或使用 ENDFILE() 检测数据结尾。文本文件存储人类可读的字符,而二进制文件以原始字节形式存储数据。

Exception handling with try-except (or try-catch) blocks prevents crashes when files are missing or permissions are insufficient. In exam scenarios, you might be asked to write pseudocode that reads a student’s scores from a file, calculates an average, and writes the report to another file. Pay attention to the logical order: open, process, close, and always validate file existence before reading.

使用 try-except(或 try-catch)块进行异常处理可防止文件缺失或权限不足时程序崩溃。在考试场景中,你可能会被要求编写伪代码,从文件中读取学生成绩、计算平均值并将报告写入另一个文件。注意逻辑顺序:打开、处理、关闭,并始终在读取前验证文件是否存在。


12. Introduction to Recursion | 递归入门

Recursion is a technique where a function calls itself to solve smaller instances of the same problem. A recursive solution requires a base case that terminates the recursion and a recursive case that moves toward the base case. For example, the factorial n! = n × (n-1)!, with base case 0! = 1. Recursion elegantly solves problems like the Tower of Hanoi, binary tree traversals, and backtracking algorithms. However, recursion can be memory-intensive due to call stack usage, so iterative solutions are sometimes preferred.

递归是一种函数调用自身以解决同一问题更小实例的技术。递归解决方案需要一个终止递归的基准情形和一个逐步逼近基准情形的递归情形。例如,阶乘 n! = n × (n-1)!,基准情形为 0! = 1。递归优雅地解决了汉诺塔、二叉树遍历和回溯算法等问题。然而,由于调用栈的使用,递归可能消耗较多内存,因此有时迭代方案更受青睐。

Tracing recursive calls requires a stack model: each call pushes a new frame with local variables, and when the base case is reached, frames pop and return values cascade back. Practice drawing the stack for a simple Fibonacci function: fib(n) = fib(n-1) + fib(n-2). Identify overlapping subproblems as an inefficiency, which leads to dynamic programming. IB exam questions on recursion usually involve trace tables and identifying the output of small recursive routines.

跟踪递归调用需要一个栈模型:每次调用将带有局部变量的新帧压入栈中,当到达基准情形时,帧弹出并逐级返回结果。练习为一个简单的斐波那契函数绘制栈:fib(n) = fib(n-1) + fib(n-2)。识别重叠子问题的低效性,这就引出了动态规划。IB 考试中关于递归的题目通常涉及跟踪表和识别小型递归例程的输出。

Recursion demands precise logic to avoid infinite loops. Always check for a condition that guarantees the recursive call simplifies the problem, such as decrementing a counter or shortening a list. Appreciate recursion’s beauty but also understand its memory cost – this balanced perspective is what examiners reward.

递归要求精确的逻辑以避免无限循环。始终检查是否存在一个条件保证递归调用简化了问题,例如递减计数器或缩短列表。欣赏递归之美,但也理解其内存成本——这种平衡的视角正是考官所嘉奖的。


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