Skip to content
Subjects
  • 1 Style and layout
    1.1

    Keywords and case

    Pseudocode 伪代码 is the language Cambridge writes algorithms 算法 in. It describes algorithms without requiring a general-purpose programming language. This site interprets a defined Cambridge-style subset so you can run examples; an exam answer should follow the notation specified for that paper.

    Every keyword 关键字 is written in upper case: IF, REPEAT, PROCEDURE, OUTPUT.

    DECLARE Count : INTEGER
    Count ← 3
    IF Count > 0
      THEN
        OUTPUT "Ready"
    ENDIF
    
    • Write IF, never if or If.
    • A keyword can never be used as a name of your own: you may not call a variable FOR.

    Common mistakes

    • Lower-case keywords. The mark scheme expects upper case.
    • Inventing keywords. Only the words in this handout are in the syllabus.
    Vocabulary
    English
    pseudocode/ˈsuːdəʊkəʊd/
    algorithms/ˈælɡərɪθəmz/
    keyword/ˈkiːwɜːd/
    1.2

    Identifiers

    An identifier 标识符 is the name you give a variable 变量, a constant 常量, a procedure 过程 or a function 函数.

    DECLARE NumberOfPlayers : INTEGER
    NumberOfPlayers ← 4
    OUTPUT NumberOfPlayers
    

    Four rules, all from the syllabus:

    • It must start with a capital letter: Count, not count.
    • It may hold only letters and digits — no spaces, no punctuation.
    • It is not case-sensitive 区分大小写, so Count and COUNT are the same name. Pick one spelling and keep it.
    • Make it mean something. NumberOfPlayers earns the reader's time; N does not.

    Common mistakes

    • count ← 0 — a lower-case start. 0478 requires the capital.
    • Number of players — spaces are not allowed inside a name.
    Vocabulary
    English
    identifier/aɪˈdentɪfaɪə/
    variable/ˈveərɪəbl/
    constant/ˈkɒnstənt/
    procedure/prəˈsiːdʒə/
    function/ˈfʌŋkʃn/
    case-sensitive/keɪs ˈsensɪtɪv/
    1.3

    Comments and indentation

    A comment 注释 starts with // and runs to the end of the line. It is for the human reader; the algorithm ignores it.

    // Swap the values of X and Y
    DECLARE X, Y, Temp : INTEGER
    X ← 1
    Y ← 2
    Temp ← X   // temporarily store X
    X ← Y
    Y ← Temp
    OUTPUT X, " ", Y
    

    Indentation 缩进 shows which statements are inside a structure. The syllabus asks for four spaces per level, with one exception you must know:

    DECLARE X, Y : INTEGER
    X ← 7
    Y ← 3
    IF X > Y
      THEN
        OUTPUT "X is bigger"
      ELSE
        OUTPUT "Y is bigger or equal"
    ENDIF
    
    • THEN and ELSE are indented two spaces from their IF.
    • The statements under them are indented four.
    • ENDIF lines up with its own IF.
    An IF-THEN-ELSE block with shaded indent bars: IF and ENDIF at the margin, THEN and ELSE two spaces in, each OUTPUT four spaces in
    Counting the spaces: 0, 2, 4

    A whole program, laid out

    The longest question on the paper asks for a complete program. Keep the same order every time, with a comment over each part, so a marker can find each mark point:

    1. a comment saying what the program does;
    2. CONSTANT lines, then every DECLARE;
    3. input, then processing, then output.
    // Mark report: the mean and the highest of five marks
    CONSTANT ClassSize ← 5
    
    DECLARE Marks : ARRAY[1:5] OF INTEGER
    DECLARE Index, Total, Highest : INTEGER
    DECLARE Mean : REAL
    
    // Input: fixed marks here; in an exam answer these lines use INPUT
    Marks[1] ← 62
    Marks[2] ← 48
    Marks[3] ← 91
    Marks[4] ← 75
    Marks[5] ← 39
    
    // Process: total the marks and keep the highest
    Total ← 0
    Highest ← Marks[1]
    FOR Index ← 1 TO ClassSize
        Total ← Total + Marks[Index]
        IF Marks[Index] > Highest
          THEN
            Highest ← Marks[Index]
        ENDIF
    NEXT Index
    Mean ← Total / ClassSize
    
    // Output
    OUTPUT "Mean mark: ", Mean
    OUTPUT "Highest mark: ", Highest
    

    Common mistakes

    • Putting THEN on the IF line. That is the A-Level 9618 layout — see topic 11.
    • No indentation at all. A marker has to see the structure to award the structure marks.
    Vocabulary
    English
    comment/ˈkɒment/
    indentation/ˌɪndenˈteɪʃn/
  • 2 Variables, constants and types
    2.1

    The five data types

    0478 pseudocode has exactly five data types 数据类型. Learn the list — naming a type that is not on it loses the mark.

    Type Holds Example
    INTEGER a whole number 整数 42, -7
    REAL a number that may have a fractional part 小数 3.14, -0.5
    CHAR a single character 单个字符 'A'
    STRING a sequence of characters 字符串 "Hello"
    BOOLEAN TRUE or FALSE 布尔值 TRUE
    DECLARE Age : INTEGER
    DECLARE Price : REAL
    DECLARE Grade : CHAR
    DECLARE Name : STRING
    DECLARE Passed : BOOLEAN
    Age ← 17
    Price ← 2.50
    Grade ← 'A'
    Name ← "Mei"
    Passed ← TRUE
    OUTPUT Name, " is ", Age, " and passed: ", Passed
    
    • A STRING is written in double quotes, a CHAR in single quotes.
    • TRUE and FALSE are keywords, so they are upper case and carry no quotes.

    Choosing the right type

    Exam questions often give some data and ask for the best type. Ask two questions: will I calculate with it? and can it have a fractional part?

    Data Type, and why
    number of students INTEGER: you count them
    height in metres REAL: 1.75 has a fractional part
    phone number "0574 8812" STRING: no calculations, and the first 0 must stay
    grade 'B' CHAR: always one character
    has the fee been paid? BOOLEAN: only yes or no

    Common mistakes

    • Writing FLOAT, DOUBLE or BOOL. Those are real languages, not this syllabus.
    • 'Hello' for a string — single quotes hold one character only.
    • Passed ← "TRUE". In quotes it is a STRING, so IF Passed = TRUE is never true. Write Passed ← TRUE.
    • A phone number as INTEGER. The leading 0 is lost, and you never add phone numbers.
    The five data types: INTEGER, REAL, CHAR, STRING and BOOLEAN
    The five data types: INTEGER, REAL, CHAR, STRING and BOOLEAN
    Vocabulary
    English
    data types/ˈdeɪtə taɪps/
    whole number/həʊl ˈnʌmbə/
    decimal part/ˈdesɪml pɑːt/
    single character/ˈsɪŋɡl ˈkærɪktə/
    sequence of characters/ˈsiːkwəns ɒv ˈkærɪktəz/
    TRUE or FALSE/ˌtiː ɑː juː ˈiː ɔː ˌef eɪ el es ˈiː/
    2.2

    DECLARE

    DECLARE names a variable 变量 and fixes its type before you use it.

    DECLARE <identifier> : <data type>
    
    DECLARE Counter : INTEGER
    DECLARE TotalToPay : REAL
    Counter ← 1
    TotalToPay ← 19.99
    OUTPUT "Item ", Counter, " costs ", TotalToPay
    

    Several names of one type go on a single line, separated by commas:

    DECLARE RoomLength, Width, Area : INTEGER
    RoomLength ← 6
    Width ← 4
    Area ← RoomLength * Width
    OUTPUT "Area = ", Area
    
    • Declare a variable before its first use, near the top of the algorithm.
    • A variable keeps its type for the whole algorithm — an INTEGER never holds "Mei".
    • Declare it before INPUT too. INPUT Mark into a variable declared INTEGER stores the number 7 when the user types 7. Without the DECLARE, the site's interpreter keeps the text "7", and IF Mark >= 50 then stops with "Cannot compare … with '>='".

    Common mistakes

    • Leaving out the colon: DECLARE Counter INTEGER.
    • Using a variable that was never declared. The exam expects the declaration.
    DECLARE names a variable and fixes the type of value it can hold
    DECLARE names a variable and fixes the type of value it can hold
    Vocabulary
    English
    variable/ˈveərɪəbl/
    2.3

    CONSTANT

    A constant 常量 is a value that is fixed for the whole algorithm — a tax rate, π, the size of a class. Naming it once means a change is made in one place.

    CONSTANT <identifier> ← <value>
    
    CONSTANT TaxRate ← 0.20
    DECLARE Price, Tax : REAL
    Price ← 50.00
    Tax ← Price * TaxRate
    OUTPUT "Tax to pay: ", Tax
    
    • In 0478 the arrow is used, exactly as for an assignment.
    • The value must be a literal 字面量 — a number, a string, TRUE — never a calculation and never another variable.
    • A constant can never be given a new value later. That is the whole point of it.

    Common mistakes

    • CONSTANT TaxRate = 0.20. The = form is the A-Level 9618 spelling — see topic 11.
    • Assigning to a constant further down the algorithm.
    Vocabulary
    English
    constant/ˈkɒnstənt/
    literal/ˈlɪtərəl/
  • 3 Assignment, input and output
    3.1

    The assignment arrow

    The assignment 赋值 operator is ←, a left-pointing arrow. It means take the value on the right and put it in the box on the left.

    <identifier> ← <value>
    
    DECLARE Counter : INTEGER
    Counter ← 0
    Counter ← Counter + 1
    Counter ← Counter + 1
    OUTPUT Counter
    

    Counter ← Counter + 1 looks impossible as mathematics and is ordinary as an instruction: work out the right-hand side with the value the box holds now, then store the result back.

    Three assignment lines beside the Counter box: 0 is stored, then 0 + 1 is worked out and 1 stored, then 1 + 1 is worked out and 2 stored
    Right side first, then store into the box
    • If you cannot type ←, write <-. Both are accepted, here and in the exam.
    • The left side must be a single identifier or one array element. Never a calculation.

    Swapping two values

    To swap two variables you need a third one to hold a value for a moment. Without it, the first assignment overwrites a value you still need.

    DECLARE First, Second, Temp : INTEGER
    First ← 3
    Second ← 8
    Temp ← First
    First ← Second
    Second ← Temp
    OUTPUT First, " ", Second
    
    Line First Second Temp
    Temp ← First 3 8 3
    First ← Second 8 8 3
    Second ← Temp 8 3 3

    Common mistakes

    • Counter = 0. In pseudocode = is a comparison, not an assignment — and confusing the two is the single commonest syntax error in this paper.
    • Counter + 1 ← Counter. The arrow points at the thing being changed.
    Vocabulary
    English
    assignment/əˈsaɪnmənt/
    3.2

    INPUT and OUTPUT

    INPUT reads a value from the user into a variable. OUTPUT displays one or more values.

    DECLARE Name : STRING
    DECLARE Age : INTEGER
    INPUT Name
    INPUT Age
    OUTPUT "Hello ", Name
    OUTPUT "Next year you will be ", Age + 1
    
    • INPUT takes exactly one variable, and that variable must already be declared.
    • OUTPUT takes any number of items separated by commas; they are printed one after another with nothing between them.
    • A literal 字面量 string in an OUTPUT goes in double quotes; a variable does not.
    • Because nothing is put between the items, a space you want on screen goes inside the quotes: OUTPUT "Hi, ", Name prints Hi, Mei; OUTPUT "Hi,", Name prints Hi,Mei.
    • Each INPUT reads one whole line. To enter three numbers, type each one and press Enter; 3 2 4 on one line is a single value, and it is not a number.

    Prompting the user

    An INPUT on its own shows nothing on screen, so a well-written algorithm prints a prompt 提示 first:

    DECLARE Radius : REAL
    OUTPUT "Enter the radius: "
    INPUT Radius
    OUTPUT "The diameter is ", Radius * 2
    
    Three statements run top to bottom, OUTPUT a prompt, INPUT Name, OUTPUT a greeting, beside the screen they produce
    The prompt appears first, then the typed answer, then the reply

    Common mistakes

    • INPUT "Enter a number", X — the prompt is a separate OUTPUT statement.
    • OUTPUT "Total: " + Total. 0478 joins output items with a comma; + is arithmetic and & belongs to A-Level 9618 (topic 11).
    • Forgetting the quotes: OUTPUT Hello looks for a variable called Hello.
    Vocabulary
    English
    literal/ˈlɪtərəl/
    prompt/prɒmpt/
  • 4 Arithmetic and logic
    4.1

    Arithmetic operators

    Five arithmetic 算术 operators; their precedence is listed below the table.

    Operator Meaning A is 7, B is 2
    + add 加 A + B is 9
    - subtract 减 A - B is 5
    * multiply 乘 A * B is 14
    / divide 除 A / B is 3.5
    ^ raise to a power 幂 A ^ B is 49
    DECLARE A, B : INTEGER
    A ← 7
    B ← 2
    OUTPUT "Sum: ", A + B
    OUTPUT "Product: ", A * B
    OUTPUT "Quotient: ", A / B
    OUTPUT "Power: ", A ^ B
    

    Brackets come first, then ^, then * and /, then + and - — the usual precedence 优先级. Use brackets whenever the reader would have to stop and think.

    Precedence ladder of brackets, power, multiply and divide, add and subtract, with (12 + 18) / 2 worked to 15 and 2 + 3 ^ 2 worked to 11
    Work down the ladder: brackets first, add and subtract last.
    DECLARE Total : REAL
    Total ← (12 + 18) / 2
    OUTPUT "Mean: ", Total
    

    Common mistakes

    • Expecting / to give a whole number. 7 / 2 is 3.5, not 3; for a whole number use DIV.
    • Writing A x B or A ÷ B. Use * and /.
    Vocabulary
    English
    arithmetic/əˈrɪθmətɪk/
    add/æd/
    subtract/sʌbˈtrækt/
    multiply/ˌmʌltɪˈplaɪ/
    divide/dɪˈvaɪd/
    raise to a power/reɪz tʊ ə ˈpaʊə/
    precedence/ˈpresɪdəns/
    4.2

    DIV and MOD

    Integer division 整数除法 answers two different questions, and 0478 writes each of them as a function 函数, with the two values in brackets.

    • DIV(a, b) — how many whole times b goes into a, the quotient 商.
    • MOD(a, b) — what is left over, the remainder 余数.
    OUTPUT DIV(10, 3)
    OUTPUT MOD(10, 3)
    OUTPUT DIV(17, 5)
    OUTPUT MOD(17, 5)
    

    Both take integers, and both return an integer.

    17 split into groups of 5: DIV gives the 3 whole groups, MOD the 2 left over
    17 split into groups of 5: DIV gives the 3 whole groups, MOD the 2 left over

    What they are for

    MOD is the standard test for divides exactly, which makes it the way to ask whether a number is even 偶数:

    DECLARE Number : INTEGER
    Number ← 12
    IF MOD(Number, 2) = 0
      THEN
        OUTPUT Number, " is even"
      ELSE
        OUTPUT Number, " is odd"
    ENDIF
    

    DIV converts a total into whole units — seconds into minutes, pence into pounds:

    DECLARE Seconds : INTEGER
    Seconds ← 200
    OUTPUT DIV(Seconds, 60), " minutes and ", MOD(Seconds, 60), " seconds"
    

    ROUND and RANDOM

    0478 has two more library routines 库函数 for numbers.

    • ROUND(Value, Places) rounds 四舍五入 Value to Places decimal places. A half goes up: ROUND(2.5, 0) is 3. With Places 0 the answer is a whole number.
    • RANDOM() gives a random number 随机数 from 0 to 1. The brackets are empty, but you must write them.
    DECLARE Price : REAL
    Price ← 3.14159
    OUTPUT ROUND(Price, 2)
    OUTPUT ROUND(Price, 0)
    OUTPUT ROUND(2.5, 0)
    

    The output is 3.14, then 3, then 3.

    This program produces whole numbers from 1 to 6, but 1 and 6 are less likely than the other outcomes, so it does not simulate a fair die 骰子.

    DECLARE Dice : INTEGER
    Dice ← ROUND(RANDOM() * 5, 0) + 1
    OUTPUT "You threw a ", Dice
    

    Run it a few times: the number changes.

    Common mistakes

    • 10 MOD 3. That is the A-Level 9618 form; 0478 uses the function form MOD(10, 3).
    • Mixing the two up. DIV gives the whole part; MOD gives what does not fit.
    • INT(X) or RAND(6). Those are A-Level 9618 names; 0478 writes ROUND(X, 0) and RANDOM().
    • RANDOM without brackets. It is a function, so it always needs ().
    Vocabulary
    English
    Integer division/ˈɪntɪdʒə dɪˈvɪʒn/
    function/ˈfʌŋkʃn/
    quotient/ˈkwəʊʃənt/
    remainder/rɪˈmeɪndə/
    even/ˈiːvən/
    library routine/ˈlaɪbrəri ruːˈtiːn/
    round/raʊnd/
    random number/ˈrændəm ˈnʌmbə/
    dice/daɪs/
    4.3

    Relational and logic operators

    A relational operator 关系运算符 compares two values and produces TRUE or FALSE.

    Operator Means
    = is equal to 等于
    <> is not equal to 不等于
    > is greater than 大于
    < is less than 小于
    >= is greater than or equal to 大于等于
    <= is less than or equal to 小于等于
    DECLARE Mark : INTEGER
    Mark ← 55
    OUTPUT "Pass: ", Mark >= 50
    OUTPUT "Perfect: ", Mark = 100
    OUTPUT "Not zero: ", Mark <> 0
    

    The three logic operators 逻辑运算符 join conditions:

    • AND — both sides must be TRUE.
    • OR — at least one side must be TRUE.
    • NOT — turns TRUE into FALSE and back.
    DECLARE Age : INTEGER
    DECLARE HasTicket : BOOLEAN
    Age ← 16
    HasTicket ← TRUE
    IF Age >= 15 AND HasTicket = TRUE
      THEN
        OUTPUT "Admitted"
    ENDIF
    IF NOT (Age > 18)
      THEN
        OUTPUT "Still a student rate"
    ENDIF
    

    Common mistakes

    • <> is the not equal sign here — not !=, which belongs to other languages.
    • IF Age >= 15 AND <= 18. Each side of AND needs its own complete comparison: Age >= 15 AND Age <= 18.
    • Calling these comparison operators in an answer. The syllabus term is relational.
    AND needs both tests TRUE: age 14 passes both, age 10 fails the first
    AND needs both tests TRUE: age 14 passes both, age 10 fails the first
    Vocabulary
    English
    relational operator/rɪˈleɪʃənl ˈɒpəreɪtə/
    is equal to/ɪz ˈiːkwl tuː/
    is not equal to/ɪz nɒt ˈiːkwl tuː/
    is greater than/ɪz ˈɡreɪtə ðən/
    is less than/ɪz les ðən/
    is greater than or equal to/ɪz ˈɡreɪtə ðən ɔː ˈiːkwl tuː/
    is less than or equal to/ɪz les ðən ɔː ˈiːkwl tuː/
    logic operators/ˈlɒdʒɪk ˈɒpəreɪtəz/
  • 5 String operations
    5.1

    LENGTH, UCASE and LCASE

    0478 publishes four string 字符串 routines and no others. Three of them are here.

    LENGTH(<identifier>) returns how many characters 字符 a string holds — spaces included.

    OUTPUT LENGTH("Happy Days")
    OUTPUT LENGTH("")
    

    UCASE(<identifier>) returns the string in upper case 大写, LCASE(<identifier>) in lower case 小写. Neither changes the original 原值 — each hands back a new value.

    DECLARE Name : STRING
    Name ← "Happy"
    OUTPUT UCASE(Name)
    OUTPUT LCASE(Name)
    OUTPUT Name
    

    That last line still prints Happy: to keep the change you must assign it back.

    DECLARE Name : STRING
    Name ← "Happy"
    Name ← UCASE(Name)
    OUTPUT Name
    

    Comparing without worrying about case

    UCASE on both sides is the standard way to accept an answer however it was typed:

    DECLARE Answer : STRING
    Answer ← "yes"
    IF UCASE(Answer) = "YES"
      THEN
        OUTPUT "Accepted"
    ENDIF
    

    Common mistakes

    • Expecting UCASE(Name) to change Name. Assign the result back.
    • LENGTH counts characters, not words. LENGTH("Happy Days") is 10.
    Vocabulary
    English
    string/strɪŋ/
    characters/ˈkærɪktəz/
    upper case/ˈʌpə keɪs/
    lower case/ˈləʊə keɪs/
    original/əˈrɪdʒɪnl/
    5.2

    SUBSTRING

    SUBSTRING(<identifier>, <start>, <length>) pulls a piece out of a string — starting at position start, taking length characters.

    OUTPUT SUBSTRING("Happy Days", 1, 5)
    OUTPUT SUBSTRING("Happy Days", 7, 4)
    

    ⚠️ Counting starts at 1, not 0. The first character of "Happy Days" is at position 1.

    Characters count from 1: SUBSTRING("Computer", 1, 4) gives "Comp"
    Characters count from 1: SUBSTRING("Computer", 1, 4) gives "Comp"

    Taking one character, and the rest

    DECLARE Word : STRING
    Word ← "Computer"
    OUTPUT "First letter: ", SUBSTRING(Word, 1, 1)
    OUTPUT "Last letter: ", SUBSTRING(Word, LENGTH(Word), 1)
    OUTPUT "Without the first: ", SUBSTRING(Word, 2, LENGTH(Word) - 1)
    

    LENGTH inside SUBSTRING is what makes the last two lines work for a word of any size — hard-coding 8 would break the moment the word changed.

    Reading a string one character at a time

    DECLARE Word : STRING
    DECLARE Index : INTEGER
    Word ← "Cat"
    FOR Index ← 1 TO LENGTH(Word)
        OUTPUT SUBSTRING(Word, Index, 1)
    NEXT Index
    

    Worked example: count the vowels

    A count 计数 starts at 0 and goes up by 1 each time the test is true. LCASE on each letter means "A" and "a" are both counted.

    DECLARE Sentence : STRING
    DECLARE Letter : CHAR
    DECLARE Index, Count : INTEGER
    Sentence ← "An Apple a day"
    Count ← 0
    FOR Index ← 1 TO LENGTH(Sentence)
        Letter ← LCASE(SUBSTRING(Sentence, Index, 1))
        IF Letter = 'a' OR Letter = 'e' OR Letter = 'i' OR Letter = 'o' OR Letter = 'u'
          THEN
            Count ← Count + 1
        ENDIF
    NEXT Index
    OUTPUT "Vowels: ", Count
    

    Trace the first three positions: "A" becomes "a" (count 1), "n" is not a vowel, the space is not a vowel. The program prints Vowels: 5.

    Worked example: a length check

    Exam questions often ask you to keep asking until the input has an allowed length. LENGTH gives the test; a REPEAT loop asks at least once. The same pattern checks a password of 8 to 20 characters: only the two numbers change.

    DECLARE Initials : STRING
    REPEAT
        OUTPUT "Enter your initials (1 to 3 characters)"
        INPUT Initials
        IF LENGTH(Initials) < 1 OR LENGTH(Initials) > 3
          THEN
            OUTPUT "Wrong length, try again"
        ENDIF
    UNTIL LENGTH(Initials) >= 1 AND LENGTH(Initials) <= 3
    OUTPUT "Thank you, ", UCASE(Initials)
    

    The UNTIL condition is the exact opposite of the error test: < becomes >=, > becomes <=, and OR becomes AND.

    Practice

    Write each answer on paper first, then open the model answer, compare, and press Run.

    1. Initials. FirstName is "Mei" and LastName is "Chen". Output the initials MC.

    Model answer
    DECLARE FirstName, LastName : STRING
    FirstName ← "Mei"
    LastName ← "Chen"
    OUTPUT SUBSTRING(FirstName, 1, 1), SUBSTRING(LastName, 1, 1)
    

    The output is MC. The first letter is always at position 1 with a length of 1, however long the name is.

    2. Count the words. Output how many words are in "I like to code". The words are separated by single spaces.

    Model answer
    DECLARE Sentence : STRING
    DECLARE Index, Spaces : INTEGER
    Sentence ← "I like to code"
    Spaces ← 0
    FOR Index ← 1 TO LENGTH(Sentence)
        IF SUBSTRING(Sentence, Index, 1) = " "
          THEN
            Spaces ← Spaces + 1
        ENDIF
    NEXT Index
    OUTPUT "Words: ", Spaces + 1
    

    The output is Words: 4. Count the spaces, then add 1: there is one more word than there are spaces between them.

    3. The name in an email. Email is "mei@school.cn". Find the position of @, then output the part before it.

    Model answer
    DECLARE Email : STRING
    DECLARE Index, AtPosition : INTEGER
    Email ← "mei@school.cn"
    AtPosition ← 0
    FOR Index ← 1 TO LENGTH(Email)
        IF SUBSTRING(Email, Index, 1) = "@"
          THEN
            AtPosition ← Index
        ENDIF
    NEXT Index
    OUTPUT "@ is at position ", AtPosition
    OUTPUT "Name: ", SUBSTRING(Email, 1, AtPosition - 1)
    

    The output is @ is at position 4, then Name: mei. The name runs from position 1 and has AtPosition - 1 characters: the third argument is a count, not an end position.

    Common mistakes

    • Starting at 0. Position 1 is the first character.
    • Reading the third argument as an end position. It is a count — SUBSTRING(W, 2, 3) takes three characters beginning at the second.
    • Asking for more characters than the string has.
    Vocabulary
    English
    count/kaʊnt/
  • 6 Selection
    6.1

    IF, THEN, ELSE, ENDIF

    Selection 选择 runs one group of statements or another, depending on a condition 条件.

    IF <condition>
      THEN
        <statements>
    ENDIF
    
    DECLARE Mark : INTEGER
    Mark ← 72
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
    ENDIF
    

    Add ELSE for the other case. Exactly one of the two branches 分支 runs — never both, never neither.

    DECLARE Mark : INTEGER
    Mark ← 41
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
      ELSE
        OUTPUT "Fail"
    ENDIF
    

    The layout is the one part students lose marks on, so learn it as a shape:

    • IF and its condition on one line, nothing after the condition.
    • THEN and ELSE on their own lines, indented two spaces.
    • The statements indented four.
    • ENDIF back at the column of its IF.
    IF chooses one of two paths; both rejoin at ENDIF
    IF chooses one of two paths; both rejoin at ENDIF

    Nesting 嵌套

    An IF inside an IF handles more than two outcomes. Each one needs its own ENDIF.

    DECLARE Mark : INTEGER
    Mark ← 85
    IF Mark >= 80
      THEN
        OUTPUT "Distinction"
      ELSE
        IF Mark >= 50
          THEN
            OUTPUT "Pass"
          ELSE
            OUTPUT "Fail"
        ENDIF
    ENDIF
    

    Test the highest boundary first. The first true condition wins, so the order matters. If the program asked Mark >= 50 first, a mark of 85 would print Pass and never reach the Distinction test.

    A range needs two comparisons joined with AND:

    DECLARE Age : INTEGER
    Age ← 15
    IF Age >= 13 AND Age <= 19
      THEN
        OUTPUT "Teenager"
      ELSE
        OUTPUT "Not a teenager"
    ENDIF
    

    IF 13 <= Age <= 19 is not allowed: each comparison needs its own variable and operator.

    Common mistakes

    • Forgetting ENDIF. Every IF closes, and a missing one is a syntax error 语法错误 the marker will see at a glance.
    • IF Mark >= 50 THEN OUTPUT "Pass" on one line. No such form exists in either syllabus; write the three lines.
    • IF Mark = 50 THEN written as IF Mark ← 50. The arrow assigns; = compares.
    Vocabulary
    English
    Selection/sɪˈlekʃn/
    condition/kənˈdɪʃn/
    branches/ˈbræntʃɪz/
    Nesting/ˈnestɪŋ/
    syntax error/ˈsɪntæks ˈerə/
    6.2

    CASE OF

    When one variable is tested against several single values, CASE OF says it far more clearly than a stack of nested IFs.

    CASE OF <identifier>
        <value 1> : <statement>
        <value 2> : <statement>
        OTHERWISE <statement>
    ENDCASE
    
    DECLARE Choice : INTEGER
    Choice ← 2
    CASE OF Choice
        1 : OUTPUT "You chose north"
        2 : OUTPUT "You chose south"
        3 : OUTPUT "You chose east"
        4 : OUTPUT "You chose west"
        OTHERWISE OUTPUT "That is not a direction"
    ENDCASE
    
    • Each branch is a value, a colon, then what to do.
    • OTHERWISE catches everything the listed values missed. It is optional, and writing one is good practice — it is what happens when the user types something unexpected.
    • The first matching branch runs, and the rest are skipped.
    CASE compares the value with each option in turn; Grade = 2 matches the second
    CASE compares the value with each option in turn; Grade = 2 matches the second

    Characters as values

    A CHAR value goes in single quotes, a STRING in double quotes.

    DECLARE Grade : CHAR
    Grade ← 'B'
    CASE OF Grade
        'A' : OUTPUT "Excellent"
        'B' : OUTPUT "Good"
        'C' : OUTPUT "Satisfactory"
        OTHERWISE OUTPUT "Unclassified"
    ENDCASE
    

    Practice

    First decide: is the test a condition (use IF) or one variable against single values (use CASE OF)? Write the answer on paper, then open the model answer, compare, and press Run.

    1. Odd or even. Number is 7. Output Odd or Even.

    Model answer
    DECLARE Number : INTEGER
    Number ← 7
    IF MOD(Number, 2) = 0
      THEN
        OUTPUT "Even"
      ELSE
        OUTPUT "Odd"
    ENDIF
    

    The output is Odd. A number is even when it divides by 2 with nothing left over, so MOD(Number, 2) = 0 is the test.

    2. A grade from a mark. 70 or more is Distinction, 50 to 69 is Merit, and below 50 is Fail. Mark is 64.

    Model answer
    DECLARE Mark : INTEGER
    Mark ← 64
    IF Mark >= 70
      THEN
        OUTPUT "Distinction"
      ELSE
        IF Mark >= 50
          THEN
            OUTPUT "Merit"
          ELSE
            OUTPUT "Fail"
        ENDIF
    ENDIF
    

    The output is Merit. These are ranges, so IF is needed, not CASE OF. The inner IF only runs when the mark is below 70, so Mark >= 50 is enough there.

    3. Weekend or weekday. Day is a number from 1 (Monday) to 7 (Sunday). Output Weekend for 6 and 7, Weekday for 1 to 5, and Not a day for anything else. Day is 6.

    Model answer
    DECLARE Day : INTEGER
    Day ← 6
    CASE OF Day
        1 : OUTPUT "Weekday"
        2 : OUTPUT "Weekday"
        3 : OUTPUT "Weekday"
        4 : OUTPUT "Weekday"
        5 : OUTPUT "Weekday"
        6 : OUTPUT "Weekend"
        7 : OUTPUT "Weekend"
        OTHERWISE OUTPUT "Not a day"
    ENDCASE
    

    The output is Weekend. One variable is tested against single values, so CASE OF fits. IGCSE CASE lists single values, so each day gets its own line; OTHERWISE catches 0, 8 and every other wrong value.

    Common mistakes

    • Using CASE OF for a condition. It tests one variable against values; Mark >= 50 needs an IF.
    • Forgetting ENDCASE.
    • Leaving out OTHERWISE and then wondering why an unexpected value does nothing at all.
    • Writing a range such as 80 TO 100 : in 0478. IGCSE CASE lists single values only; test a range with IF Mark >= 80 AND Mark <= 100. (A-Level 9618 does allow 80 TO 100 :.)
  • 7 Iteration
    7.1

    FOR, the counted loop

    Iteration 迭代 repeats statements. Use a FOR loop when you know before you start how many times — a count-controlled 计数控制 loop.

    FOR <identifier> ← <value1> TO <value2>
        <statements>
    NEXT <identifier>
    
    DECLARE Index : INTEGER
    FOR Index ← 1 TO 5
        OUTPUT "Line ", Index
    NEXT Index
    

    The counter 计数器 starts at the first value, and the loop runs once for every value up to and including the second. 1 TO 5 runs five times.

    FOR Count ← 1 TO 4 runs four passes, and both 1 and 4 are included
    FOR Count ← 1 TO 4 runs four passes, and both 1 and 4 are included

    STEP

    STEP changes the size of each jump. A negative step counts down.

    DECLARE Index : INTEGER
    FOR Index ← 2 TO 10 STEP 2
        OUTPUT Index
    NEXT Index
    FOR Index ← 3 TO 1 STEP -1
        OUTPUT "Countdown ", Index
    NEXT Index
    

    Running totals

    The commonest use: a variable outside the loop that the loop adds to.

    DECLARE Index, Total : INTEGER
    Total ← 0
    FOR Index ← 1 TO 10
        Total ← Total + Index
    NEXT Index
    OUTPUT "Sum of 1 to 10 is ", Total
    

    Total ← 0 must sit before the loop. Inside, it would reset on every pass.

    Totalling, counting and the largest value

    A typical paper 2 task reads several values and reports on them. Each job has a variable set before the loop, updated inside it and output after it:

    DECLARE Index, Mark, Total, Passes, Highest : INTEGER
    Total ← 0
    Passes ← 0
    Highest ← -1
    FOR Index ← 1 TO 5
        OUTPUT "Enter mark ", Index
        INPUT Mark
        Total ← Total + Mark
        IF Mark >= 50
          THEN
            Passes ← Passes + 1
        ENDIF
        IF Mark > Highest
          THEN
            Highest ← Mark
        ENDIF
    NEXT Index
    OUTPUT "Average: ", Total / 5
    OUTPUT "Passes: ", Passes
    OUTPUT "Highest: ", Highest
    

    Highest ← -1 works because every mark is at least 0, so the first mark always replaces it. When there is no such lower limit, start from the first value instead.

    Common mistakes

    • NEXT naming the wrong counter. Nested loops must close in the reverse order they opened: the inner NEXT first.
    • Assuming 1 TO 5 runs four times. Both ends are included.
    • Changing the counter inside the loop. Let FOR own it.
    Vocabulary
    English
    Iteration/ˌɪtəˈreɪʃn/
    count-controlled/kaʊnt kənˈtrəʊld/
    counter/ˈkaʊntə/
    7.2

    WHILE, the pre-condition loop

    A WHILE loop tests before each pass, so it can run zero times. Use it when the number of repeats depends on something that happens while the loop runs.

    WHILE <condition> DO
        <statements>
    ENDWHILE
    
    DECLARE Total : INTEGER
    Total ← 1
    WHILE Total < 100 DO
        Total ← Total * 2
    ENDWHILE
    OUTPUT "First power of two past 100: ", Total
    

    Something inside the loop must eventually make the condition false, or the loop never ends — an infinite loop 无限循环.

    DECLARE Count : INTEGER
    Count ← 5
    WHILE Count > 0 DO
        OUTPUT Count
        Count ← Count - 1
    ENDWHILE
    OUTPUT "Lift off"
    

    Common mistakes

    • Forgetting to change the variable the condition tests, giving an infinite loop.
    • Leaving out DO or ENDWHILE.
    • Using WHILE where the count is known. A FOR says what you mean in one line.
    Vocabulary
    English
    infinite loop/ˈɪnfɪnət luːp/
    7.3

    REPEAT, the post-condition loop

    A REPEAT loop tests after each pass, so it always runs at least once.

    REPEAT
        <statements>
    UNTIL <condition>
    

    That "at least once" is the reason to choose it: validating 验证 input, where you must ask before you can judge the answer.

    DECLARE Number : INTEGER
    Number ← 0
    REPEAT
        Number ← Number + 25
        OUTPUT "Trying ", Number
    UNTIL Number >= 100
    OUTPUT "Reached ", Number
    

    A real validation loop asks again until the answer is in range:

    DECLARE Rating : INTEGER
    REPEAT
        OUTPUT "Rate the lesson from 1 to 10: "
        INPUT Rating
        IF Rating < 1 OR Rating > 10
          THEN
            OUTPUT "Please enter a whole number from 1 to 10"
        ENDIF
    UNTIL Rating >= 1 AND Rating <= 10
    OUTPUT "Thank you: ", Rating
    

    The UNTIL condition describes a good answer; the IF inside describes a bad one, so the two conditions are opposites.

    ⚠️ UNTIL states the condition that stops the loop; WHILE states the one that keeps it going. They are opposites, and swapping them is the classic error.

    Tests Runs at least once? Condition means
    FOR a counter no (an empty range runs zero times) —
    WHILE before no keep going while this is true
    REPEAT after yes stop when this becomes true

    Common mistakes

    • Writing UNTIL Number < 100 when you mean UNTIL Number >= 100.
    • Using REPEAT where the body must be able to run zero times.
    • Forgetting that UNTIL ends the structure — there is no ENDREPEAT.
    WHILE tests first and may run zero times; REPEAT tests last and runs at least once
    WHILE tests first and may run zero times; REPEAT tests last and runs at least once

    Practice: choose the loop, then write it

    Each task needs a different loop. Decide which one first, then write the answer on paper, then open the model answer, compare, and press Run.

    1. A times table. Output the 7 times table from 1 x 7 = 7 to 10 x 7 = 70.

    Model answer
    DECLARE Count : INTEGER
    FOR Count ← 1 TO 10
        OUTPUT Count, " x 7 = ", Count * 7
    NEXT Count
    

    Why FOR: you know before the loop starts that it runs exactly 10 times.

    2. Doubling savings. Savings of 100 grow by 10% each year. Output how many years it takes to reach 200 or more.

    Model answer
    DECLARE Savings : REAL
    DECLARE Years : INTEGER
    Savings ← 100
    Years ← 0
    WHILE Savings < 200 DO
        Savings ← Savings * 1.1
        Years ← Years + 1
    ENDWHILE
    OUTPUT Years, " years"
    

    The output is 8 years. Why WHILE: you do not know the number of passes in advance; the loop stops when a condition changes. If the savings already started at 200, the loop would correctly run zero times.

    3. Add up the digits. Output the sum of the digits of 4071 (4 + 0 + 7 + 1).

    Model answer
    DECLARE Number, Total : INTEGER
    Number ← 4071
    Total ← 0
    REPEAT
        Total ← Total + MOD(Number, 10)
        Number ← DIV(Number, 10)
    UNTIL Number = 0
    OUTPUT Total
    

    The output is 12. MOD(Number, 10) is the last digit; DIV(Number, 10) removes it. Why REPEAT: every whole number has at least one digit, so the body must run at least once. The UNTIL condition says when to stop: when no digits are left.

    Vocabulary
    English
    validating/ˈvælɪdeɪtɪŋ/
  • 8 Arrays
    8.1

    One-dimensional arrays

    An array 数组 holds many values of one type under one name. Each value sits at an index 下标.

    DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>
    
    DECLARE Names : ARRAY[1:3] OF STRING
    Names[1] ← "Mei"
    Names[2] ← "Sam"
    Names[3] ← "Ana"
    OUTPUT Names[2]
    
    • The bounds 边界 are written lower:upper, and both are included — [1:3] has three elements 元素.
    • Cambridge arrays normally start at 1, not 0.
    • Every element has the same type, fixed by OF.
    A 1-D array: one name, many values, each found by its index
    A 1-D array: one name, many values, each found by its index

    Filling and reading with a FOR loop

    An array and a counted loop belong together: the counter is the index.

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index, Total : INTEGER
    FOR Index ← 1 TO 5
        Scores[Index] ← Index * 10
    NEXT Index
    Total ← 0
    FOR Index ← 1 TO 5
        Total ← Total + Scores[Index]
    NEXT Index
    OUTPUT "Total: ", Total
    OUTPUT "Mean: ", Total / 5
    

    Finding the largest

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index, Largest : INTEGER
    Scores[1] ← 42
    Scores[2] ← 17
    Scores[3] ← 93
    Scores[4] ← 8
    Scores[5] ← 55
    Largest ← Scores[1]
    FOR Index ← 2 TO 5
        IF Scores[Index] > Largest
          THEN
            Largest ← Scores[Index]
        ENDIF
    NEXT Index
    OUTPUT "Largest: ", Largest
    

    Start Largest at the first element, never at 0 — with negative data, 0 would win and the answer would be wrong.

    Linear search: is a value in the array?

    A linear search 线性查找 checks the elements one by one, from the first, until it finds the value or reaches the end. A BOOLEAN flag 标志 remembers whether it was found, and a WHILE loop stops early once it is.

    DECLARE Names : ARRAY[1:5] OF STRING
    DECLARE Index : INTEGER
    DECLARE Found : BOOLEAN
    DECLARE Wanted : STRING
    Names[1] ← "Mei"
    Names[2] ← "Sam"
    Names[3] ← "Ana"
    Names[4] ← "Tom"
    Names[5] ← "Lin"
    Wanted ← "Ana"
    Found ← FALSE
    Index ← 1
    WHILE Found = FALSE AND Index <= 5 DO
        IF Names[Index] = Wanted
          THEN
            Found ← TRUE
          ELSE
            Index ← Index + 1
        ENDIF
    ENDWHILE
    IF Found = TRUE
      THEN
        OUTPUT Wanted, " found at position ", Index
      ELSE
        OUTPUT Wanted, " not found"
    ENDIF
    

    The test Index <= 5 stops the loop at the end of the array, so a missing name never reads Names[6]. Here the output is Ana found at position 3.

    Bubble sort: put the array in order

    A bubble sort 冒泡排序 compares each pair of neighbours. If they are in the wrong order, it swaps 交换 them, using a Temp variable to hold one value. After one pass the largest value has reached the end, so each pass checks one element fewer. When a whole pass makes no swap, the array is sorted and the loop stops.

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index : INTEGER
    DECLARE Last : INTEGER
    DECLARE Temp : INTEGER
    DECLARE Swapped : BOOLEAN
    Scores[1] ← 42
    Scores[2] ← 7
    Scores[3] ← 31
    Scores[4] ← 18
    Scores[5] ← 25
    Last ← 4
    REPEAT
        Swapped ← FALSE
        FOR Index ← 1 TO Last
            IF Scores[Index] > Scores[Index + 1]
              THEN
                Temp ← Scores[Index]
                Scores[Index] ← Scores[Index + 1]
                Scores[Index + 1] ← Temp
                Swapped ← TRUE
            ENDIF
        NEXT Index
        Last ← Last - 1
    UNTIL Swapped = FALSE OR Last = 0
    FOR Index ← 1 TO 5
        OUTPUT Scores[Index]
    NEXT Index
    

    The output is 7, 18, 25, 31, 42, one per line. The loop goes only to Last, never to 5, because it reads Scores[Index + 1]. The three lines with Temp are the swap: without Temp, the first value would be lost.

    Common mistakes

    • Reading Scores[6] from an array declared [1:5]. That is out of bounds 越界.
    • Writing Scores(3). Arrays use square brackets; round brackets call a function.
    • Declaring [1:5] and then looping 0 TO 4.
    • Using the array's name as the loop counter: FOR Scores ← 1 TO 5. The counter is a separate INTEGER, such as Index, and it goes inside the brackets: Scores[Index].
    • Empty brackets, Scores[]. Every use of one element needs its index.
    • IF Scores[Index] THEN. A condition needs a comparison, such as IF Scores[Index] > 50.

    Practice

    Write each answer on paper first, then open the model answer, compare, and press Run. Each task uses the array Scores[1:6], which holds 64, 38, 91, 50, 27, 75 in that order: Scores[1] is 64 and Scores[6] is 75.

    1. Count the passes. A pass is a score of 50 or more. Output how many scores pass.

    Model answer
    DECLARE Scores : ARRAY[1:6] OF INTEGER
    DECLARE Index, Passes : INTEGER
    Scores[1] ← 64
    Scores[2] ← 38
    Scores[3] ← 91
    Scores[4] ← 50
    Scores[5] ← 27
    Scores[6] ← 75
    Passes ← 0
    FOR Index ← 1 TO 6
        IF Scores[Index] >= 50
          THEN
            Passes ← Passes + 1
        ENDIF
    NEXT Index
    OUTPUT Passes, " scores pass"
    

    The output is 4 scores pass. The test is >=, not >: a score of exactly 50 passes. This is the counting pattern: start at 0 and add 1 each time the test is true.

    2. Backwards. Output the six scores from the last to the first.

    Model answer
    DECLARE Scores : ARRAY[1:6] OF INTEGER
    DECLARE Index : INTEGER
    Scores[1] ← 64
    Scores[2] ← 38
    Scores[3] ← 91
    Scores[4] ← 50
    Scores[5] ← 27
    Scores[6] ← 75
    FOR Index ← 6 TO 1 STEP -1
        OUTPUT Scores[Index]
    NEXT Index
    

    STEP -1 makes the counter go down: 6, 5, 4, 3, 2, 1. Without it, a loop from 6 to 1 does not run at all.

    3. Where is the lowest score? Output the lowest score and its position.

    Model answer
    DECLARE Scores : ARRAY[1:6] OF INTEGER
    DECLARE Index, Lowest, Position : INTEGER
    Scores[1] ← 64
    Scores[2] ← 38
    Scores[3] ← 91
    Scores[4] ← 50
    Scores[5] ← 27
    Scores[6] ← 75
    Lowest ← Scores[1]
    Position ← 1
    FOR Index ← 2 TO 6
        IF Scores[Index] < Lowest
          THEN
            Lowest ← Scores[Index]
            Position ← Index
        ENDIF
    NEXT Index
    OUTPUT "Lowest: ", Lowest, " at position ", Position
    

    The output is Lowest: 27 at position 5. Keep two variables: the value and where it was. Both change together, inside the same IF. Exam questions often ask for the position, and an answer that keeps only the value loses that mark.

    Vocabulary
    English
    array/əˈreɪ/
    index/ˈɪndeks/
    bounds/baʊndz/
    elements/ˈelɪmənts/
    out of bounds/ˈaʊtəv baʊndz/
    linear search/ˈlɪnɪə sɜːtʃ/
    flag/flæɡ/
    bubble sort/ˈbʌbl sɔːt/
    swap/swɒp/
    8.2

    Two-dimensional arrays

    A 2-D array 二维数组 is a table: rows and columns, two indexes.

    DECLARE <identifier> : ARRAY[<lower1>:<upper1>, <lower2>:<upper2>] OF <data type>
    
    DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
    Grid[1,1] ← 1
    Grid[1,2] ← 2
    Grid[1,3] ← 3
    Grid[2,1] ← 4
    Grid[2,2] ← 5
    Grid[2,3] ← 6
    OUTPUT Grid[2,3]
    

    The first index is the row 行, the second the column 列.

    A 2-D array is a grid: G[1, 2] is row 1, column 2
    A 2-D array is a grid: G[1, 2] is row 1, column 2

    Nested loops walk a table

    One loop per dimension 维度. The inner loop finishes a whole row before the outer moves on.

    DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
    DECLARE Row, Col : INTEGER
    FOR Row ← 1 TO 2
        FOR Col ← 1 TO 3
            Grid[Row, Col] ← Row * Col
        NEXT Col
    NEXT Row
    FOR Row ← 1 TO 2
        FOR Col ← 1 TO 3
            OUTPUT "Grid[", Row, ",", Col, "] = ", Grid[Row, Col]
        NEXT Col
    NEXT Row
    

    ⚠️ The inner NEXT closes the inner counter. NEXT Row before NEXT Col crosses the loops over and is nonsense — a marker spots it instantly.

    Common mistakes

    • Swapping row and column. Grid[2,3] is row 2, column 3.
    • Grid[Row][Col]. Cambridge writes one pair of brackets with a comma inside.
    • Crossing the NEXT lines over, as above.
    Vocabulary
    English
    2-D array/tuː diː əˈreɪ/
    row/rəʊ/
    column/ˈkɒlʌm/
    dimension/daɪˈmenʃn/
  • 9 Procedures and functions
    9.1

    PROCEDURE and CALL

    A procedure 过程 is a named block of statements. Writing one once and calling it from several places is decomposition 分解 — the idea the whole of paper 2 rests on.

    PROCEDURE <identifier>
        <statements>
    ENDPROCEDURE
    

    A procedure is called by name, with the keyword CALL:

    PROCEDURE DefaultLine
        OUTPUT "------------------------------"
    ENDPROCEDURE
    
    CALL DefaultLine
    OUTPUT "Report"
    CALL DefaultLine
    
    • The definition 定义 does nothing on its own. Only CALL runs it.
    • Control returns to the line after the CALL when the procedure ends.
    • A procedure does not give a value back. If you need one, you want a function.

    Common mistakes

    • Writing DefaultLine on its own to run it. 0478 requires CALL.
    • Leaving out ENDPROCEDURE.
    • Expecting the procedure's own variables to exist outside it.
    Vocabulary
    English
    procedure/prəˈsiːdʒə/
    decomposition/ˌdiːkɒmpəˈzɪʃn/
    definition/ˌdefɪˈnɪʃn/
    9.2

    FUNCTION and RETURN

    A function 函数 is a named routine that returns a value. It is written where that value is needed — inside an OUTPUT, on the right of an assignment, inside a condition.

    FUNCTION <identifier>(<parameters>) RETURNS <data type>
        <statements>
        RETURN <value>
    ENDFUNCTION
    
    FUNCTION SumSquare(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
        RETURN Number1 * Number1 + Number2 * Number2
    ENDFUNCTION
    
    OUTPUT "Sum of squares = ", SumSquare(10, 20)
    
    • RETURNS <data type> on the header says what type comes back. It is not optional.
    • RETURN ends the function immediately — nothing after it runs.
    • A function is never called with CALL; it is used wherever its value belongs.
    A procedure is CALLed to do a job; a function returns a value to use
    A procedure is CALLed to do a job; a function returns a value to use

    A function inside a condition

    FUNCTION IsEven(Number : INTEGER) RETURNS BOOLEAN
        RETURN MOD(Number, 2) = 0
    ENDFUNCTION
    
    DECLARE Index : INTEGER
    FOR Index ← 1 TO 6
        IF IsEven(Index)
          THEN
            OUTPUT Index, " is even"
        ENDIF
    NEXT Index
    

    What happens in a call

    Follow OUTPUT "Sum of squares = ", SumSquare(10, 20):

    Step What happens
    1 10 is copied into Number1 and 20 into Number2
    2 the function works out 10 * 10 + 20 * 20, which is 500
    3 RETURN hands 500 back; the call SumSquare(10, 20) now stands for 500
    4 OUTPUT prints Sum of squares = 500

    The parameters already hold the values from the call, so do not INPUT them again inside the function. Inside the body use the parameter names; the function's own name is only for calling it.

    Lines students write, and the correct form

    Wrong Right
    RETURNS Number * 2 in the body RETURN Number * 2 (RETURNS is only in the header)
    RETURN ← Total RETURN Total
    Doubled ← Number * 2 RETURN Number * 2
    IF MOD(Number, 2) == 0 IF MOD(Number, 2) = 0
    OUTPUT Doubled("7") OUTPUT Doubled(7) ("7" is text)
    END FUNCTION ENDFUNCTION
    Doubled(7) alone on a line OUTPUT Doubled(7) or Answer ← Doubled(7)

    Common mistakes

    • CALL SumSquare(10, 20) — CALL invokes a procedure, not a function. Use the function in an expression, such as Answer ← SumSquare(10, 20).
    • A function with no RETURN on some path. Every route out must return a value.
    • Leaving RETURNS INTEGER off the header.

    Practice

    First decide: does the task give back a value (a function) or do a job (a procedure)? Write the answer on paper, then open the model answer, compare, and press Run.

    1. The larger number. Write Larger(A, B), which gives back the larger of two integers. Output Larger(12, 7).

    Model answer
    FUNCTION Larger(A : INTEGER, B : INTEGER) RETURNS INTEGER
        IF A > B
          THEN
            RETURN A
          ELSE
            RETURN B
        ENDIF
    ENDFUNCTION
    
    OUTPUT Larger(12, 7)
    

    The output is 12. A function, because the task gives back a value. Both paths of the IF return something.

    2. A countdown. Write Countdown(Start), which outputs the numbers from Start down to 1 and then Go!. Use it to count down from 3.

    Model answer
    PROCEDURE Countdown(Start : INTEGER)
        DECLARE Number : INTEGER
        FOR Number ← Start TO 1 STEP -1
            OUTPUT Number
        NEXT Number
        OUTPUT "Go!"
    ENDPROCEDURE
    
    CALL Countdown(3)
    

    The output is 3, 2, 1, Go!, one per line. A procedure, because it does a job (outputs lines) and gives nothing back, so it is run with CALL.

    3. A grade. Write Grade(Mark), which returns "A" for 70 or more, "B" for 50 to 69 and "U" below 50. Output the grades for 85, 50 and 12.

    Model answer
    FUNCTION Grade(Mark : INTEGER) RETURNS STRING
        IF Mark >= 70
          THEN
            RETURN "A"
        ENDIF
        IF Mark >= 50
          THEN
            RETURN "B"
        ENDIF
        RETURN "U"
    ENDFUNCTION
    
    OUTPUT Grade(85)
    OUTPUT Grade(50)
    OUTPUT Grade(12)
    

    The output is A, B, U. RETURN ends the function at once, so a mark of 85 never reaches the second test. The last line runs only when both tests were false, and it makes sure every path returns a value. Test the boundary, 50: it must give B.

    Vocabulary
    English
    function/ˈfʌŋkʃn/
    9.3

    Parameters

    A parameter 参数 is a value a procedure or function is given when it is called. Each one carries its own type.

    PROCEDURE Line(Size : INTEGER)
        DECLARE Index : INTEGER
        FOR Index ← 1 TO Size
            OUTPUT "-"
        NEXT Index
    ENDPROCEDURE
    
    CALL Line(5)
    CALL Line(20)
    

    Several parameters are separated by commas, and the order at the call must match the order in the definition:

    PROCEDURE Greet(Name : STRING, Times : INTEGER)
        DECLARE Index : INTEGER
        FOR Index ← 1 TO Times
            OUTPUT "Hello ", Name
        NEXT Index
    ENDPROCEDURE
    
    CALL Greet("Mei", 2)
    CALL Greet("Sam", 1)
    

    ⚠️ In 0478 every parameter is passed by value 传值: the procedure works on a copy, so changing it inside changes nothing outside. To get a value back, use a FUNCTION and RETURN it. (A-Level 9618 adds BYREF for the other behaviour — topic 11.)

    Pass by value copies the caller's x = 5 into the parameter, so changing it leaves x at 5; pass by reference points the parameter at x, so x changes too
    0478 uses the left side only: the procedure gets a copy.
    FUNCTION Doubled(Number : INTEGER) RETURNS INTEGER
        RETURN Number * 2
    ENDFUNCTION
    
    DECLARE Value : INTEGER
    Value ← 7
    Value ← Doubled(Value)
    OUTPUT Value
    

    Common mistakes

    • PROCEDURE Line(Size) with no type.
    • Calling with the arguments in the wrong order — Greet(2, "Mei") is a type error.
    • Expecting a procedure to change the variable you passed in. In 0478 it cannot.
    Vocabulary
    English
    parameter/pəˈræmɪtə/
    passed by value/pæst baɪ ˈvæljuː/
  • 10 File handling
    10.1

    Writing to a file

    A file 文件 keeps data after the program ends. 0478 uses four commands, and every one names the file it works on.

    OPENFILE <file identifier> FOR WRITE
    WRITEFILE <file identifier>, <data>
    CLOSEFILE <file identifier>
    
    OPENFILE "names.txt" FOR WRITE
    WRITEFILE "names.txt", "Mei"
    WRITEFILE "names.txt", "Sam"
    CLOSEFILE "names.txt"
    OUTPUT "Saved"
    

    Three file modes 文件模式:

    Mode What it does
    WRITE start a new file — anything already there is lost
    APPEND 追加 add to the end of what is there
    READ read from the start
    OPENFILE "log.txt" FOR WRITE
    WRITEFILE "log.txt", "first"
    CLOSEFILE "log.txt"
    OPENFILE "log.txt" FOR APPEND
    WRITEFILE "log.txt", "second"
    CLOSEFILE "log.txt"
    OUTPUT "Both lines saved"
    
    • One WRITEFILE writes one line.
    • CLOSEFILE is not optional. An unclosed file can lose the data still waiting to be written, and that is a stock exam answer.
    log.txt after FOR WRITE holds first; after FOR APPEND it holds first and second; had the second open used FOR WRITE, only second would remain
    APPEND keeps what is there; a second WRITE would have wiped it.

    Saving an array

    A FOR loop writes one element per line. Reading the file back shows one value on each line:

    DECLARE Scores : ARRAY[1:4] OF INTEGER
    DECLARE Index : INTEGER
    Scores[1] ← 12
    Scores[2] ← 30
    Scores[3] ← 7
    Scores[4] ← 25
    OPENFILE "scores.txt" FOR WRITE
    FOR Index ← 1 TO 4
        WRITEFILE "scores.txt", Scores[Index]
    NEXT Index
    CLOSEFILE "scores.txt"
    
    DECLARE Line : STRING
    OPENFILE "scores.txt" FOR READ
    WHILE NOT EOF("scores.txt") DO
        READFILE "scores.txt", Line
        OUTPUT Line
    ENDWHILE
    CLOSEFILE "scores.txt"
    
    • WRITEFILE sits inside the loop; OPENFILE and CLOSEFILE stay outside it, so the file is opened once and closed once.

    Common mistakes

    • FOR WRITE when you meant FOR APPEND, which silently destroys the old contents.
    • Forgetting CLOSEFILE.
    • Opening a file that is already open.
    • Leaving out the quotes round the file name. A file name is text, so it needs double quotes: OPENFILE "names.txt" FOR WRITE.
    Vocabulary
    English
    file/faɪl/
    file modes/faɪl məʊdz/
    APPEND/əˈpend/
    10.2

    Reading a file to the end

    READFILE takes one line into a variable. The variable must be declared first.

    OPENFILE <file identifier> FOR READ
    READFILE <file identifier>, <variable>
    CLOSEFILE <file identifier>
    

    Normally you do not know how many lines there are, so you read until the end of the file — which is what the EOF function reports.

    OPENFILE "names.txt" FOR WRITE
    WRITEFILE "names.txt", "Mei"
    WRITEFILE "names.txt", "Sam"
    WRITEFILE "names.txt", "Ana"
    CLOSEFILE "names.txt"
    
    DECLARE Line : STRING
    OPENFILE "names.txt" FOR READ
    WHILE NOT EOF("names.txt") DO
        READFILE "names.txt", Line
        OUTPUT Line
    ENDWHILE
    CLOSEFILE "names.txt"
    

    EOF("names.txt") is TRUE once every line has been read, so WHILE NOT EOF(...) means while there is still something to read.

    Open a file for WRITE or READ, use it line by line, then close it
    Open a file for WRITE or READ, use it line by line, then close it

    Counting while reading

    OPENFILE "marks.txt" FOR WRITE
    WRITEFILE "marks.txt", 40
    WRITEFILE "marks.txt", 65
    WRITEFILE "marks.txt", 88
    CLOSEFILE "marks.txt"
    
    DECLARE Mark, Count, Total : INTEGER
    Count ← 0
    Total ← 0
    OPENFILE "marks.txt" FOR READ
    WHILE NOT EOF("marks.txt") DO
        READFILE "marks.txt", Mark
        Count ← Count + 1
        Total ← Total + Mark
    ENDWHILE
    CLOSEFILE "marks.txt"
    OUTPUT Count, " marks, mean ", Total / Count
    

    Searching a file: stop when found

    To find one value, read until it turns up or the file ends. A BOOLEAN flag 标志 Found records that the value has turned up, and the loop stops at once:

    OPENFILE "members.txt" FOR WRITE
    WRITEFILE "members.txt", "Ana"
    WRITEFILE "members.txt", "Ben"
    WRITEFILE "members.txt", "Lin"
    WRITEFILE "members.txt", "Tom"
    CLOSEFILE "members.txt"
    
    DECLARE Name, Wanted : STRING
    DECLARE Found : BOOLEAN
    Wanted ← "Ben"
    Found ← FALSE
    OPENFILE "members.txt" FOR READ
    WHILE NOT EOF("members.txt") AND NOT Found DO
        READFILE "members.txt", Name
        IF Name = Wanted
          THEN
            Found ← TRUE
        ENDIF
    ENDWHILE
    CLOSEFILE "members.txt"
    IF Found
      THEN
        OUTPUT Wanted, " is a member"
      ELSE
        OUTPUT Wanted, " is not a member"
    ENDIF
    
    Name read Found
    Ana FALSE: go on
    Ben TRUE: stop

    After Ben, NOT Found is FALSE, so the loop stops: Lin and Tom are never read. Without AND NOT Found the loop would read them anyway, which wastes time on a long file.

    Two files at once: copy the lines you want

    A program can have one file open FOR READ and another FOR WRITE. Each command names the file it uses, so they never mix:

    OPENFILE "marks.txt" FOR WRITE
    WRITEFILE "marks.txt", 40
    WRITEFILE "marks.txt", 65
    WRITEFILE "marks.txt", 88
    WRITEFILE "marks.txt", 52
    CLOSEFILE "marks.txt"
    
    DECLARE Mark : INTEGER
    OPENFILE "marks.txt" FOR READ
    OPENFILE "passed.txt" FOR WRITE
    WHILE NOT EOF("marks.txt") DO
        READFILE "marks.txt", Mark
        IF Mark >= 50
          THEN
            WRITEFILE "passed.txt", Mark
        ENDIF
    ENDWHILE
    CLOSEFILE "marks.txt"
    CLOSEFILE "passed.txt"
    
    DECLARE Line : STRING
    OPENFILE "passed.txt" FOR READ
    WHILE NOT EOF("passed.txt") DO
        READFILE "passed.txt", Line
        OUTPUT Line
    ENDWHILE
    CLOSEFILE "passed.txt"
    
    • 40 is below 50, so it is the only mark not copied into passed.txt.
    • Close both files. passed.txt must be closed before it is opened again FOR READ.

    Common mistakes

    • A WHILE EOF(...) loop — that runs only when there is nothing left. You want NOT.
    • Reading past the end because the loop has no EOF guard.
    • Opening FOR READ a file that does not exist.
    • Opening a file again without closing it first. CLOSEFILE, then OPENFILE in the new mode.
    Vocabulary
    English
    flag/flæɡ/
  • 11 A-Level 9618: what changes
    11.1

    Layout and operators

    Cambridge publishes two pseudocode specifications, and they disagree. Everything in topics 1-10 is IGCSE 0478. A-Level 9618 changes the details below — and a student who studies both loses marks by writing one in the other's paper.

    IGCSE 0478 A-Level 9618
    THEN on its own line, indented 2 on the IF line
    constants CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD functions: DIV(10, 3) operators: 10 DIV 3
    joining strings commas in OUTPUT the & operator
    identifiers must start with a capital mixed case allowed 混合大小写
    NEXT must name its counter good practice
    ROUND, RANDOM() both published neither exists

    Some built-in routines have different names. The playground names the right one if you use the other syllabus's name:

    IGCSE 0478 A-Level 9618
    SUBSTRING(S, 2, 3) MID(S, 2, 3)
    SUBSTRING(S, 1, 3) LEFT(S, 3)
    UCASE(S) TO_UPPER(S)
    RANDOM(): 0 to 1 RAND(10): 0 up to 10
    ROUND(X, 0) rounds INT(X) cuts off

    This is the 0478 form, and it runs here:

    DECLARE Total : REAL
    CONSTANT Rate ← 0.5
    Total ← 10
    IF MOD(7, 2) = 1
      THEN
        OUTPUT "Odd, half rate ", Total * Rate
    ENDIF
    

    The 9618 form of the same algorithm is written like this — note THEN on the IF line, = in the CONSTANT, and MOD between its two values:

    DECLARE Total : REAL
    CONSTANT Rate = 0.5
    Total ← 10
    IF 7 MOD 2 = 1 THEN
        OUTPUT "Odd, " & "half rate ", Total * Rate
    ENDIF
    

    ⚠️ The two syllabuses use different published pseudocode conventions. In an exam, make your algorithm clear and unambiguous. The playground on this page runs the 0478 rules, so a 9618 construct is refused with a message naming the syllabus it belongs to — which is a quick way to check your own habits.

    Common mistakes

    • Writing THEN on the IF line in an 0478 answer, because that is what a textbook or a website showed. It is the single commonest cross-syllabus slip.
    • 10 MOD 3 in 0478. There it is MOD(10, 3).
    • ROUND(3.14159, 2) in a 9618 answer. 9618 has no ROUND at all.
    • SUBSTRING in a 9618 answer, or MID in an 0478 answer. Learn the names for your paper.
    Vocabulary
    English
    mixed case/mɪkst keɪs/
    11.2

    Parameters: BYVAL and BYREF

    0478 passes every parameter by value 传值 (topic 9). 9618 lets you choose, and says so in the header.

    • BYVAL — the procedure gets a copy. Changing it changes nothing outside. This is the default when neither word is written.
    • BYREF — the procedure works on the caller's own variable 原变量 by reference, so a change is visible after the call.

    This is 9618 only. It does not run here, and it is not accepted in an 0478 answer:

    PROCEDURE Increase(BYREF Value : INTEGER)
        Value ← Value + 1
    ENDPROCEDURE
    
    DECLARE Count : INTEGER
    Count ← 5
    CALL Increase(Count)
    OUTPUT Count      // prints 6
    
    BYVAL passes a copy; BYREF lets the procedure change the caller's variable
    BYVAL passes a copy; BYREF lets the procedure change the caller's variable

    The 0478 way to get a value back

    Use a FUNCTION and assign what it returns. This is the whole of the 0478 answer, and it runs:

    FUNCTION Increased(Value : INTEGER) RETURNS INTEGER
        RETURN Value + 1
    ENDFUNCTION
    
    DECLARE Count : INTEGER
    Count ← 5
    Count ← Increased(Count)
    OUTPUT Count
    

    Common mistakes

    • Writing BYREF in an 0478 answer. The keyword is not in that syllabus.
    • Expecting a plain 9618 parameter to behave like BYREF. Without the word it is BYVAL.
    Vocabulary
    English
    by value/baɪ ˈvæljuː/
    own variable/əʊn ˈveərɪəbl/
    11.3

    Records and other types

    9618 has data structures 数据结构 that 0478 does not. You will meet them only at A-Level, and none of them runs under the 0478 rules of this page.

    A record 记录 groups fields of different types under one name (9618 section 4):

    TYPE Student
        DECLARE Name : STRING
        DECLARE Mark : INTEGER
    ENDTYPE
    
    DECLARE Candidate : Student
    Candidate.Name ← "Mei"
    Candidate.Mark ← 91
    OUTPUT Candidate.Name, " scored ", Candidate.Mark
    

    An enumerated type 枚举类型 lists the only values a variable may take:

    TYPE Vehicle = (Car, Bus, Taxi)
    DECLARE MyRide : Vehicle
    MyRide ← Taxi
    

    9618 also adds a DATE data type, random-access files (OPENFILE … FOR RANDOM), pointers, and classes with CLASS … ENDCLASS for its object-oriented paper.

    ⚠️ 0478 has five data types and arrays, and nothing else (topic 2). A 0478 answer that declares a record is answering a different syllabus.

    Common mistakes

    • Using a record in an 0478 answer. Use parallel arrays instead — one array per field, sharing an index.
    • Thinking TYPE means the same as DECLARE. TYPE defines a new type; DECLARE creates a variable of an existing one.
    A record groups fields of different types; dot notation reaches each one
    A record groups fields of different types; dot notation reaches each one
    Vocabulary
    English
    data structures/ˈdeɪtə ˈstrʌktʃəz/
    record/ˈrekɔːd/
    enumerated type/ɪˈnjuːməreɪtɪd taɪp/

Log in or create account

IGCSE, A-Level & AP