Skip to content

Programming

A-Level Computer Science · Topic 11

Train
11.1

Programming basics

Syllabus
Candidates should be able to: Notes and guidance
Implement and write pseudocode from a given design presented as either a program flowchart or structured English
Write pseudocode statements for: • the declaration and initialisation of constants • the declaration of variables • the assignment of values to variables • expressions involving any of the arithmetic or logical operators input from the keyboard and output to the console
Use built-in functions and library routines Any functions not given in the pseudocode guide will be provided String manipulation functions will always be given

Source: Cambridge International syllabus

Lines of source code on a dark screen Programming turns a design into instructions written as code

A programmer working at a computer A programmer writes the code and tests it as they go

From design to code

You should be able to turn a design — a flowchart 流程图 (program flowchart) or structured English 结构化英语 — into pseudocode 伪代码, and then into a real language:

  1. find the variables 变量 and their data types 数据类型.
  2. turn input/output boxes into INPUT / OUTPUT.
  3. turn decision diamonds into IF...ELSE...ENDIF (or CASE).
  4. turn loop arrows into WHILE, REPEAT...UNTIL, or FOR.
  5. turn process boxes into assignments or calculations.
  6. check by tracing a small input.

A mapping from flowchart symbols to pseudocode: an input/output parallelogram becomes INPUT or OUTPUT, a decision diamond becomes IF...THEN or CASE, a process box becomes an assignment x = expression, and a loop arrow becomes WHILE, FOR or REPEAT Each flowchart symbol becomes a pseudocode keyword

Constants and variables

A constant 常量 holds a value that never changes; a variable holds one that may change. Declare them with a type:

A variable's value can change; a constant stays fixed A variable's value can change; a constant stays fixed

CONSTANT Pi ← 3.14159
DECLARE Radius : REAL
DECLARE Area : REAL

Radius ← 5
Area ← Pi * Radius * Radius

Use constants for fixed values that recur (Pi, MaxScore); they make code clearer and easy to change in one place.

Assignment and expressions

Use for assignment 赋值:

Total ← Total + 1
Average ← Sum / Count

Expressions use operators 运算符:

  • arithmetic + - * /, plus DIV (integer division) and MOD (remainder): 7 DIV 2 = 3; 7 MOD 2 = 1.
  • comparisons =, <>, <, >, <=, >=.
  • logic AND, OR, NOT.

Precedence 优先级 (highest to lowest): NOT* / DIV MOD+ - → comparisons → ANDOR. Use brackets when unsure.

Input and output

OUTPUT "Enter your name:"
INPUT Name
OUTPUT "Hello, ", Name

Built-in functions and library routines

Many tasks have ready-made library routines 库例程, so you need not write them:

  • string: LENGTH(s), LEFT(s, n), RIGHT(s, n), MID(s, start, len), UCASE(s), LCASE(s).
  • numeric: INT(x), ROUND(x), ABS(x), MOD(a, b), RANDOM().
  • conversion: STR(x) (number → string), VAL(s) (string → number).

Use the exact names from the question paper's reference list.

The string COMPUTER shown as eight numbered character boxes (positions 1 to 8), with worked results: LENGTH(s) = 8, LEFT(s, 3) = COM, MID(s, 4, 3) = PUT, RIGHT(s, 2) = ER, and UCASE/LCASE changing the letter case The common string routines acting on s = "COMPUTER" (positions 1–8)

Explore

A variable is a labelled box

Each assignment stores one value in a named box; reassigning the same name overwrites it. Step through the program and watch each box take its current value.

Vocabulary Train
English Chinese Pinyin
flowchart 流程图 liú chéng tú
structured English 结构化英语 jié gòu huà yīng yǔ
pseudocode 伪代码 wěi dài mǎ
variables 变量 biàn liàng
data types 数据类型 shù jù lèi xíng
constant 常量 cháng liàng
assignment 赋值 fù zhí
operators 运算符 yùn suàn fú
precedence 优先级 yōu xiān jí
library routines 库例程 kù lì chéng
11.2

Selection

Syllabus
Candidates should be able to: Notes and guidance
Use pseudocode to write: • an ‘IF’ statement including the ‘ELSE’ clause and nested IF statements • a ‘CASE’ structure • a ‘count-controlled’ loop: • a ‘post-condition’ loop • a ‘pre-condition’ loop
Justify why one loop structure may be better suited to solve a problem than the others

Source: Cambridge International syllabus

Selection 选择 chooses which steps run.

IF age >= 18 THEN
    OUTPUT "Adult"
ELSE
    OUTPUT "Minor"
ENDIF

A flowchart: from start, a decision diamond tests age >= 18; the TRUE branch outputs Adult and the FALSE branch outputs Minor, and both rejoin at end An IF...ELSE tests the condition once, then runs exactly one branch

For more than two cases you can use a nested 嵌套 IF, but deep nesting is hard to read — a CASE is cleaner when testing one value against several options:

CASE OF Grade
    "A": OUTPUT "Excellent"
    "B": OUTPUT "Good"
    OTHERWISE: OUTPUT "Try again"
ENDCASE

Cambridge CASE allows single values, value lists (1, 2, 3:), and ranges (1 TO 5:).

A flowchart of a CASE OF Grade statement: the value is tested against each guard in turn (a single value, a value list, then a range); the first matching branch runs its statement, otherwise the OTHERWISE branch runs, and all branches rejoin at ENDCASE A CASE statement runs the branch that matches the value

Explore

Selection (IF / ELSE)

Change the input and see which branch runs — the essence of selection.

Vocabulary Train
English Chinese Pinyin
selection 选择 xuǎn zé
nested 嵌套 qiàn tào
11.2

Iteration

Iteration 迭代 repeats a block. Three loops differ in how many times the body runs.

Count-controlled (FOR) loop

A count-controlled loop 计数循环 — use it when you know how many times to repeat:

FOR i ← 1 TO 10
    OUTPUT i
NEXT i

A STEP can change the count (e.g. FOR i ← 10 TO 1 STEP -1). Best for a fixed number of repeats or processing each element of an array 数组.

Pre-condition (WHILE) loop

A pre-condition loop 前测循环 tests the condition before each pass, so it may run zero times:

WHILE total < 100 DO
    INPUT n
    total ← total + n
ENDWHILE

Post-condition (REPEAT...UNTIL) loop

A post-condition loop 后测循环 tests the condition after each pass, so it always runs at least once:

REPEAT
    INPUT password
UNTIL password = correctPassword

Choosing the right loop

Three flowchart columns. FOR: a count box (i = 1 to N) then a body box, looping back, for a set number of passes. WHILE: a test diamond above a body box, so the condition is checked before the body and the loop may run zero times. REPEAT: a body box above a test diamond, so the condition is checked after the body and the loop runs at least once The three loops differ in where the condition is tested — before the body (WHILE), after it (REPEAT), or a set number of times (FOR)

  • count known up front → FOR.
  • may need zero passes → WHILE.
  • always at least one pass → REPEAT...UNTIL.

Justify your choice by whether the count is known and whether the body must run at least once. A typical question gives a scenario ("ask for a password until correct, but always ask at least once") and asks which loop fits.

Explore

Trace a loop, pass by pass

A trace table records each variable after every pass of the loop. Watch the counter i climb while the running total builds up — exactly what an exam trace question asks you to fill in.

Explore

Tracing a loop

Step through the loop and watch the variables change each pass — exactly what a trace table records.

Vocabulary Train
English Chinese Pinyin
iteration 迭代 dié dài
count-controlled loop 计数循环 jì shù xún huán
array 数组 shù zǔ
pre-condition loop 前测循环 qián cè xún huán
post-condition loop 后测循环 hòu cè xún huán
11.3

Procedures and functions

Syllabus
Candidates should be able to: Notes and guidance
Define and use a procedure
Explain where in the construction of an algorithm it would be appropriate to use a procedure
Use parameters A procedure may have none, one or more parameters A parameter can be passed by reference or by value
Define and use a function
Explain where in the construction of an algorithm it is appropriate to use a function A function is used in an expression, e.g. the return value replaces the call
Use the terminology associated with procedures and functions including procedure/function header, procedure/function interface, parameter, argument, return value
Write efficient pseudocode

Source: Cambridge International syllabus

Structured programming 结构化编程 builds a program from small named subroutines 子程序, each with one job.

Procedure

A procedure 过程 is a named block that does an action; it may take parameters 参数 but does not return a value.

PROCEDURE Greet(name : STRING)
    OUTPUT "Hello, ", name
ENDPROCEDURE

CALL Greet("Ada")

Function

A function 函数 is like a procedure but it returns a value that becomes part of an expression.

FUNCTION Square(x : INTEGER) RETURNS INTEGER
    RETURN x * x
ENDFUNCTION

result ← Square(5) + 1     // result = 26

Use a procedure when the subroutine performs an action; use a function when it computes a value for the caller.

Two panels. Procedure: call Greet(Ada) does an action and prints Hello, Ada, returning no value. Function: set y = Square(5) computes 5 times 5 = 25, returns 25, so y then holds 25 A procedure does an action and returns nothing; a function returns a value you use in an expression

Parameters

A parameter is a variable a subroutine declares to receive input; the values the caller supplies are arguments 实参. Two ways to pass them:

  • pass by value 传值 — the routine gets a copy; changes inside it do not affect the caller. Use for inputs it only reads.
  • pass by reference 传引用 — the routine gets a reference to the caller's variable; changes do affect the caller. Use when it must update a parameter.

Two memory-box diagrams. Pass by value: the caller's variable x = 5 is copied into a separate parameter box a = 5, so changing a leaves x as 5. Pass by reference: the parameter a is an arrow pointing to the caller's own x box, so changing a changes x too Pass by value copies the value into a new box; pass by reference lets the routine change the caller's own variable

PROCEDURE Swap(BYREF a : INTEGER, BYREF b : INTEGER)
    DECLARE temp : INTEGER
    temp ← a
    a ← b
    b ← temp
ENDPROCEDURE

Local vs global variables

A local variable 局部变量 is declared inside a subroutine and exists only while it runs. A global variable 全局变量 is declared outside and is visible everywhere. Prefer locals and parameters — heavy use of globals makes code hard to follow and test. (The region where a name is visible is its scope 作用域.)

A large outer box labelled global scope holds the global variable Total, visible everywhere, and a smaller inner box labelled PROCEDURE Calc, local scope, holds the local variable temp, which exists only while Calc runs A global variable is visible everywhere; a local variable exists only inside its own procedure

When to use a subroutine

Use a subroutine when:

  • the same logic appears in more than one place — write it once, call it many times.
  • a block has a clear named purpose — the name documents what it does.
  • the program is complex — break it into parts (decomposition 分解).
  • you want to test a piece in isolation.

Don't make them so tiny that the call costs more than the work inside.

Terminology

  • definition — the PROCEDURE ... ENDPROCEDURE (or function) block.
  • call — where it is invoked. argument — a value passed in. parameter — the variable that receives it.
  • return value — what a function passes back.
  • procedure/function header — the first line giving the name and parameters (PROCEDURE Name(params) or FUNCTION Name(params) RETURNS type).
  • procedure/function interface / signature 签名 — name + parameters + return type: what a caller must know to use it.

Worked example. Which loop suits each task? (a) print the 12 times table; (b) keep reading numbers until the user enters 0; (c) ask for a password until it is correct. Choose by asking how many times the body runs and when the test happens. (a) The count is known in advance (12), so use a FOR loop. (b) The count is unknown, and the very first input might already be 0 - so the test must come before the body: a WHILE loop, which runs zero or more times. (c) The count is unknown, but you must always ask at least once before there is anything to test - so the test comes after the body: a REPEAT...UNTIL, which runs one or more times. The deciding question is whether the body must run at least once: WHILE may run zero times, REPEAT always runs once.

Explore

The call stack: push on call, pop on return

Calling a subroutine pushes a new frame on top; returning pops it and hands a value back to the caller. The call that is running is always the frame on top.

Vocabulary Train
English Chinese Pinyin
structured programming 结构化编程 jié gòu huà biān chéng
subroutines 子程序 zi chéng xù
procedure 过程 guò chéng
parameters 参数 cān shù
function 函数 hán shù
arguments 实参 shí cān
pass by value 传值 chuán zhí
pass by reference 传引用 chuán yǐn yòng
local variable 局部变量 jú bù biàn liàng
global variable 全局变量 quán jú biàn liàng
scope 作用域 zuò yòng yù
decomposition 分解 fēn jiě
signature 签名 qiān míng
11.3

Writing efficient pseudocode

  • move invariants out of loops — if a value (an invariant 不变量) does not change with the loop counter, compute it once before the loop.
  • exit a loop early when the answer is found (stop a linear search 线性查找 as soon as the target appears).
  • avoid redundant work — store a result and reuse it instead of recomputing.
  • choose the right data structure — an array beats many separate variables when the items belong together.
  • replace deep nested IFs with CASE when testing one value against many.
  • comment the intent, not the mechanics (// validate the postcode, not // loop 6 times).
  • use meaningful names (numberOfPupils, not n) and initialise variables before use.

Move work that never changes out of the loop, so it runs once instead of every pass Move unchanging work out of the loop so it runs once

Vocabulary Train
English Chinese Pinyin
invariant 不变量 bù biàn liàng
linear search 线性查找 xiàn xìng chá zhǎo
11.3

Exam tips

  • Distinguish a procedure (no return value) from a function (returns a value); know pass by value vs by reference.
  • Choose the right loop: count-controlled (FOR) when the number of repeats is known, condition-controlled (WHILE/REPEAT) otherwise.
  • Distinguish local vs global variables and scope; prefer local variables in reusable modules.

Log in or create account

IGCSE & A-Level