Skip to content · ⁨Passer au contenu⁩
Subjects · ⁨Sujets⁩
  • 1 Style and layout · ⁨Style et mise en page⁩
    1.1

    Mots-clés et casse

    English

    Pseudocode 伪代码 is the language Cambridge writes algorithms 算法 in. It is not a real programming language — no computer runs it — but the exam marks it as if it were, so the form matters.

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

    • 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.
    Français

    Le pseudocode 伪代码 est le langage dans lequel Cambridge écrit les algorithmes 算法. Ce n'est pas un langage réel. langage de programmation — aucun ordinateur ne l'exécute — mais l'examen le note comme si c'était le cas, donc la forme est importante.

    Chaque mot clé 关键字 s'écrit en MAJUSCULES : IF, REPEAT, PROCEDURE, OUTPUT.

    DECLARE Count : INTEGER
    Count ← 3
    IF Count > 0
      THEN
        OUTPUT "Ready"
    ENDIF
    
    • Écrivez IF, jamais if ou If.
    • Un mot clé ne peut jamais être utilisé comme nom personnel : vous ne pouvez pas appeler une variable FOR.

    Erreurs courantes

    • Mots clés en minuscules. La grille d'évaluation attend des majuscules.
    • Invention de mots clés. Seuls les mots de cette fiche font partie du programme.
    1.2

    Identifiants

    English

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

    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.
    Français

    Un identifiant 标识符 est le nom que vous donnez à une variable 变量, une constante 常量, une procédure 过程 or a function 函数.

    DECLARE NumberOfPlayers : INTEGER
    NumberOfPlayers ← 4
    OUTPUT NumberOfPlayers
    

    Quatre règles, toutes issues du programme :

    • Il doit commencer par une majuscule : Count, pas count.
    • Il ne peut contenir que des lettres et des chiffres — pas d'espaces, pas de ponctuation.
    • Il n'est pas sensible à la casse 不区分大小写, donc Count et COUNT sont le même nom. Choisissez une orthographe et tenez-y bon.
    • Faites qu'il ait un sens. NumberOfPlayers mérite le temps du lecteur ; N non.

    Erreurs courantes

    • count ← 0 — début en minuscule. 0478 exige la majuscule.
    • Number of players — les espaces ne sont pas autorisés dans un nom.
    1.3

    Commentaires et indentation

    English

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

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

    • THEN and ELSE are indented two spaces from their IF.
    • The statements under them are indented four.
    • ENDIF lines up with its own IF.

    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.
    Français

    Un commentaire 注释 commence par // et se poursuit jusqu'à la fin de la ligne. C'est pour l'humain lecteur ; l'algorithme l'ignore.

    // 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
    

    L'indentation 缩进 indique quelles instructions sont à l'intérieur d'une structure. Le programme demande quatre espaces par niveau, avec une exception que vous devez connaître :

    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 et ELSE sont indentés de deux espaces par rapport à leur IF.
    • Les instructions qui les suivent sont indentées de quatre.
    • ENDIF est aligné avec son propre IF.

    Erreurs courantes

    • Placer THEN sur la ligne IF. C'est la mise en page A-Level 9618 — voir sujet 11.
    • Aucune indentation du tout. Un correcteur doit voir la structure pour accorder les points de structure.
  • 2 Variables, constants and types · ⁨Variables, constantes et types⁩
    2.1

    Les cinq types de données

    English

    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 with a decimal part 小数 3.14, -0.5
    CHAR a single character 单个字符 'A'
    STRING a sequence of characters 字符串 "Hello"
    BOOLEAN TRUE or FALSE 布尔值 TRUE
    • 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.

    Common mistakes

    • Writing FLOAT, DOUBLE or BOOL. Those are real languages, not this syllabus.
    • 'Hello' for a string — single quotes hold one character only.
    Français

    Le pseudocode 0478 a exactement cinq types de données 数据类型. Apprenez la liste — nommer un type qui n'y figure pas fait perdre le point.

    Type Holds Example
    INTEGER un nombre entier 整数 42, -7
    REAL un nombre avec une partie décimale 小数 3.14, -0.5
    CHAR un seul caractère 单个字符 'A'
    STRING une séquence de caractères 字符串 "Hello"
    BOOLEAN TRUE ou FALSE valeurs booléennes 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
    
    • Un STRING s'écrit entre guillemets double, un CHAR entre guillemets simple.
    • TRUE et FALSE sont des mots clés, donc ils sont en majuscules et ne portent pas de guillemets.

    Erreurs courantes

    • Écrire FLOAT, DOUBLE ou BOOL. Ce sont de vrais langages, pas ce programme.
    • 'Hello' pour une chaîne — les guillemets simples ne tiennent qu'un seul caractère.
    2.2

    DECLARE

    English

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

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

    • 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".

    Common mistakes

    • Leaving out the colon: DECLARE Counter INTEGER.
    • Using a variable that was never declared. The exam expects the declaration.
    Français

    DECLARE nomme une variable 变量 et fixe son type avant de l'utiliser.

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

    Plusieurs noms d'un même type peuvent aller sur une seule ligne, séparés par des virgules :

    DECLARE Length, Width, Area : INTEGER
    Length ← 6
    Width ← 4
    Area ← Length * Width
    OUTPUT "Area = ", Area
    
    • Déclare une variable avant sa première utilisation, près du haut de l'algorithme.
    • Une variable conserve son type tout au long de l'algorithme — un INTEGER ne contient jamais "Mei".

    Erreurs courantes

    • Omettre les deux-points : DECLARE Counter INTEGER.
    • Utiliser une variable qui n'a jamais été déclarée. L'examen exige la déclaration.
    2.3

    CONSTANT

    English

    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.

    • 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.
    Français

    Une constante 常量 est une valeur fixée pour tout l'algorithme — un taux de taxe, π, la taille d'une classe. La nommer une fois signifie qu'un changement se fait à un seul endroit.

    CONSTANT <identifier> ← <value>
    
    CONSTANT TaxRate ← 0.20
    DECLARE Price, Tax : REAL
    Price ← 50.00
    Tax ← Price * TaxRate
    OUTPUT "Tax to pay: ", Tax
    
    • En 0478 on utilise la flèche, exactement comme pour une affectation.
    • La valeur doit être un littéral 字面量 — un nombre, une chaîne, TRUE — jamais un calcul et jamais une autre variable.
    • Une constante ne peut jamais recevoir une nouvelle valeur plus tard. C'est toute son utilité.

    Erreurs courantes

    • CONSTANT TaxRate = 0.20. La forme = est l'orthographe A-Level 9618 — voir sujet 11.
    • Affecter à une constante plus loin dans l'algorithme.
  • 3 Assignment, input and output · ⁨Affectation, entrée et sortie⁩
    3.1

    La flèche d'affectation

    English

    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.

    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.

    • 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.

    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.
    Français

    L'opérateur d'affectation 赋值 est ←, une flèche pointant vers la gauche. Cela signifie prendre la valeur à droite et la mettre dans la boîte à gauche.

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

    Counter ← Counter + 1 semble impossible en mathématiques et est ordinaire comme instruction : calculez le côté droit avec la valeur que la boîte contient maintenant, puis stockez le résultat dedans.

    • Si vous ne pouvez pas taper ←, écrivez <-. Les deux sont acceptés, ici et à l'examen.
    • Le côté gauche doit être un identifiant unique ou un élément de tableau. Jamais un calcul.

    Erreurs courantes

    • Counter = 0. En pseudocode = est une comparaison, pas une affectation — et confondre les deux est l'erreur de syntaxe la plus fréquente dans cette épreuve.
    • Counter + 1 ← Counter. La flèche pointe vers la chose qui change.
    3.2

    INPUT and OUTPUT · ⁨INPUT et OUTPUT⁩

    English

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

    • 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.

    Prompting the user

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

    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.
    Français

    INPUT lit une valeur depuis l'utilisateur dans une variable. OUTPUT affiche une ou plusieurs valeurs.

    DECLARE Name : STRING
    DECLARE Age : INTEGER
    INPUT Name
    INPUT Age
    OUTPUT "Hello ", Name
    OUTPUT "Next year you will be ", Age + 1
    
    • INPUT prend exactement une variable, et cette variable doit déjà être déclarée.
    • OUTPUT prend n'importe quel nombre d'éléments séparés par des virgules ; ils sont imprimés l'un après l'autre sans rien entre eux.
    • Un littéral 字面量 chaîne dans un OUTPUT va entre guillemets doubles ; une variable non.

    Inviter l'utilisateur

    Un INPUT seul n'affiche rien à l'écran, donc un algorithme bien écrit affiche d'abord une invite 提示:

    DECLARE Radius : REAL
    OUTPUT "Enter the radius: "
    INPUT Radius
    OUTPUT "The diameter is ", Radius * 2
    

    Erreurs courantes

    • INPUT "Enter a number", X — l'invite est une instruction OUTPUT séparée.
    • OUTPUT "Total: " + Total. 0478 joint les éléments de sortie avec une virgule ; + est une arithmétique et & appartient au A-Level 9618 (sujet 11).
    • Oublier les guillemets : OUTPUT Hello cherche une variable nommée Hello.
  • 4 Arithmetic and logic · ⁨Arithmétique et logique⁩
    4.1

    Opérateurs arithmétiques

    English

    Five arithmetic 算术 operators, in the order a calculator uses them.

    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

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

    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 /.
    Français

    Cinq opérateurs arithmétiques 算术, dans l'ordre qu'utilise une calculatrice.

    Opérateur Signification A vaut 7, B vaut 2
    + addition 加 A + B vaut 9
    - soustraction 减 A - B vaut 5
    * multiplication 乘 A * B vaut 14
    / division 除 A / B vaut 3.5
    ^ puissance 幂 A ^ B vaut 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
    

    Les parenthèses viennent en premier, puis ^, puis * et /, puis + et - — la priorité 优先级. Utilisez des parenthèses chaque fois que le lecteur devrait s'arrêter pour réfléchir.

    DECLARE Total : REAL
    Total ← (12 + 18) / 2
    OUTPUT "Mean: ", Total
    

    Erreurs courantes

    • Attendre que / donne un nombre entier. 7 / 2 est 3.5, pas 3 ; pour un nombre entier utilisez DIV.
    • Écrire A x B ou A ÷ B. Utilisez * et /.
    4.2

    DIV and MOD · ⁨DIV et MOD⁩

    English

    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 余数.

    Both take integers, and both return an integer.

    What they are for

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

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

    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.
    Français

    La division entière 整数除法 répond à deux questions différentes, et 0478 écrit chacune d'elles comme un fonction 函数, avec les deux valeurs entre parenthèses.

    • DIV(a, b) — combien de fois b tient dans a, le quotient 商.
    • MOD(a, b) — ce qu'il reste, le reste 余数.
    OUTPUT DIV(10, 3)
    OUTPUT MOD(10, 3)
    OUTPUT DIV(17, 5)
    OUTPUT MOD(17, 5)
    

    Les deux prennent des entiers, et les deux retournent un entier.

    À quoi elles servent

    MOD est le test standard pour divise exactement, ce qui en fait le moyen de demander si un nombre est pair 偶数 :

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

    DIV convertit un total en unités entières — secondes en minutes, pence en livres :

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

    Erreurs courantes

    • 10 MOD 3. C'est la forme A-Level 9618 ; 0478 utilise la forme fonction MOD(10, 3).
    • Mélanger les deux. DIV donne la partie entière ; MOD donne ce qui ne rentre pas.
    4.3

    Opérateurs relationnels et logiques

    English

    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 小于等于

    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.

    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.
    Français

    Un opérateur relationnel 关系运算符 compare deux valeurs et produit TRUE ou FALSE.

    Opérateur Signifie
    = est égal à 等于
    <> est différent de 不等于
    > est supérieur à 大于
    < est inférieur à 小于
    >= est supérieur ou égal à 大于等于
    <= est inférieur ou égal à 小于等于
    DECLARE Mark : INTEGER
    Mark ← 55
    OUTPUT "Pass: ", Mark >= 50
    OUTPUT "Perfect: ", Mark = 100
    OUTPUT "Not zero: ", Mark <> 0
    

    Les trois opérateurs logiques 逻辑运算符 joignent des conditions :

    • AND — les deux côtés doivent être TRUE.
    • OR — au moins un côté doit être TRUE.
    • NOT — transforme TRUE en FALSE et vice versa.
    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
    

    Erreurs courantes

    • <> est le signe différent de ici — pas !=, qui appartient à d'autres langages.
    • IF Age >= 15 AND <= 18. Chaque côté de AND nécessite sa propre comparaison complète : Age >= 15 AND Age <= 18.
    • Appeler ces opérateurs de comparaison dans une réponse. Le terme du programme est relationnel.
  • 5 String operations · ⁨Opérations sur les chaînes⁩
    5.1

    LENGTH, UCASE and LCASE · ⁨LENGTH, UCASE et LCASE⁩

    English

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

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

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

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

    Comparing without worrying about case

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

    Common mistakes

    • Expecting UCASE(Name) to change Name. Assign the result back.
    • LENGTH counts characters, not words. LENGTH("Happy Days") is 10.
    Français

    0478 publie quatre routines de chaînes 字符串 et aucune autre. Trois d'entre elles sont ici.

    LENGTH(<identifier>) retourne combien de caractères 字符 une chaîne contient — espaces inclus.

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

    UCASE(<identifier>) retourne la chaîne en MAJUSCULES 大写, LCASE(<identifier>) en minuscules case 小写. Aucun ne modifie la valeur originale — chacun retourne une nouvelle valeur.

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

    Cette dernière ligne imprime toujours Happy : pour garder le changement, vous devez l'affecter en retour.

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

    Comparer sans se soucier de la casse

    UCASE des deux côtés est la méthode standard pour accepter une réponse quelle que soit sa frappe :

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

    Erreurs courantes

    • Attendre que UCASE(Name) modifie Name. Affectez le résultat en retour.
    • LENGTH compte les caractères, pas les mots. LENGTH("Happy Days") vaut 10.
    5.2

    SUBSTRING

    English

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

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

    Taking one character, and the rest

    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

    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.
    Français

    SUBSTRING(<identifier>, <start>, <length>) extrait une portion d'une chaîne — en commençant à la position start, en prenant length caractères.

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

    ⚠️ Le comptage commence à 1, pas 0. Le premier caractère de "Happy Days" est à la position 1.

    Prendre un seul caractère, et le reste

    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 à l'intérieur de SUBSTRING est ce qui rend les deux dernières lignes fonctionnelles pour un mot de taille quelconque — durcir 8 casserait dès que le mot changerait.

    Lire une chaîne un caractère à la fois

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

    Erreurs courantes

    • Commence à 0. La position 1 est le premier caractère.
    • Lire le troisième argument comme une position de fin. C'est un compte — SUBSTRING(W, 2, 3) prend trois caractères en partant du deuxième.
    • Demander plus de caractères que la chaîne ne contient.
  • 6 Selection · ⁨Sélection⁩
    6.1

    SI, ALORS, SINON, FINSI

    English

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

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

    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.

    Nesting 嵌套

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

    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.
    Français

    Sélection 选择 exécute un groupe d'instructions ou un autre, selon une condition 条件.

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

    Ajouter ELSE pour l'autre cas. Exactement une des deux branches 分支 s'exécute — jamais les deux, jamais aucune.

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

    La mise en page est la seule partie où les élèves perdent des points, apprenez-la comme une forme :

    • IF et sa condition sur une même ligne, rien après la condition.
    • THEN et ELSE sur leurs propres lignes, indentés de deux espaces.
    • Les instructions indentées de quatre.
    • ENDIF revient à la colonne de son IF.

    Emboîtement 嵌套

    Un IF dans un IF gère plus de deux issues. Chacun a besoin de son propre ENDIF.

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

    Erreurs courantes

    • Oublier ENDIF. Chaque IF se ferme, et un manquant est une erreur de syntaxe 语法错误 que le marqueur verra instantanément.
    • IF Mark >= 50 THEN OUTPUT "Pass" sur une seule ligne. Aucune telle forme n'existe ni dans programme ; écrivez les trois lignes.
    • IF Mark = 50 THEN écrit comme IF Mark ← 50. La flèche assigne ; = compare.
    6.2

    CAS DE

    English

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

    • 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.

    A range, and a character

    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.
    Français

    Quand une variable est testée contre plusieurs valeurs uniques, CASE OF l'exprime bien plus clairement qu'une pile d'emboîtements 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
    
    • Chaque branche est une valeur, un deux-points, puis ce qu'il faut faire.
    • OTHERWISE attrape tout ce que les valeurs listées ont manqué. C'est optionnel, et en écrire un est une bonne pratique — c'est ce qui se passe quand l'utilisateur tape quelque chose d'inattendu.
    • La première branche correspondante s'exécute, et les autres sont ignorées.

    Une plage, et un caractère

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

    Erreurs courantes

    • Utiliser CASE OF pour une condition. Elle teste une variable contre des valeurs ; Mark >= 50 nécessite un IF.
    • Oublier ENDCASE.
    • Omettre OTHERWISE puis se demander pourquoi une valeur inattendue ne fait rien du tout.
  • 7 Iteration · ⁨Itération⁩
    7.1

    POUR, la boucle comptée

    English

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

    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.

    STEP

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

    Running totals

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

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

    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.
    Français

    Itération 迭代 répète des instructions. Utilisez une boucle FOR lorsque vous savez avant de commencer combien de fois — une boucle à contrôle de comptage 计数控制.

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

    Le compteur 计数器 commence à la première valeur, et la boucle s'exécute une fois pour chaque valeur jusqu'à et en incluant la seconde. 1 TO 5 s'exécute cinq fois.

    PAS

    STEP change la taille de chaque saut. Un pas négatif compte vers le bas.

    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
    

    Sommes cumulées

    L'usage le plus courant : une variable hors de la boucle à laquelle la boucle ajoute.

    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 doit se situer avant la boucle. À l'intérieur, il serait réinitialisé à chaque passage.

    Erreurs courantes

    • NEXT nommant le mauvais compteur. Les boucles imbriquées doivent se fermer dans l'ordre inverse de celui où elles s'ouvrent : l'inner NEXT d'abord.
    • Supposer que 1 TO 5 s'exécute quatre fois. Les deux extrémités sont incluses.
    • Modifier le compteur à l'intérieur de la boucle. Laissez FOR en être propriétaire.
    7.2

    TANT QUE, la boucle pré-condition

    English

    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.

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

    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.
    Français

    Une boucle WHILE teste avant chaque passage, donc elle peut s'exécuter zéro fois. Utilisez-la lorsque le nombre de répétitions dépend de quelque chose qui se produit pendant l'exécution de la boucle.

    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
    

    Quelque chose à l'intérieur de la boucle doit finalement rendre la condition fausse, sinon la boucle ne finit jamais — un boucle infinie 无限循环.

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

    Erreurs courantes

    • Oublier de modifier la variable testée par la condition, provoquant une boucle infinie.
    • Omettre DO ou ENDWHILE.
    • Utiliser WHILE lorsque le comptage est connu. Un FOR exprime votre sens en une seule ligne.
    7.3

    RÉPÉTER, la boucle post-condition

    English

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

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

    ⚠️ 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.
    Français

    Une boucle REPEAT teste après chaque passage, donc elle s'exécute toujours au moins une fois.

    REPEAT
        <statements>
    UNTIL <condition>
    

    Ce « au moins une fois » est la raison de la choisir : valider 验证 l'entrée, où vous devez demander avant de pouvoir juger la réponse.

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

    ⚠️ UNTIL énonce la condition qui arrête la boucle ; WHILE énonce celle qui la maintient active. Elles sont opposées, et les inverser est l'erreur classique.

    Teste S'exécute au moins une fois ? Condition signifie
    FOR un compteur non (une plage vide s'exécute zéro fois) —
    WHILE avant non continuer tant que ceci est vrai
    REPEAT après oui arrêter lorsque ceci devient vrai

    Erreurs courantes

    • Écrire UNTIL Number < 100 au lieu de UNTIL Number >= 100.
    • Utiliser REPEAT là où le corps doit pouvoir s'exécuter zéro fois.
    • Oublier que UNTIL termine la structure — il n'y a pas de ENDREPEAT.
  • 8 Arrays · ⁨Tableaux⁩
    8.1

    Tableaux unidimensionnels

    English

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

    • 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.

    Filling and reading with a FOR loop

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

    Finding the largest

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

    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.
    Français

    Un tableau 数组 contient de nombreuses valeurs d'un même type sous un seul nom. Chaque valeur est placée à un 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]
    
    • Les bornes 边界 sont écrites lower:upper, et les deux sont incluses — [1:3] a trois éléments 元素.
    • Les tableaux Cambridge commencent normalement à 1, pas 0.
    • Chaque élément a le même type, défini par OF.

    Remplir et lire avec une boucle POUR

    Un tableau et une boucle comptée vont ensemble : le compteur est l'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
    

    Trouver le plus grand

    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
    

    Commencez Largest au premier élément, jamais à 0 — avec des données négatives, 0 gagnerait et la réponse serait fausse.

    Erreurs courantes

    • Lire Scores[6] depuis un tableau déclaré [1:5]. C'est hors limites 越界.
    • Écrire Scores(3). Les tableaux utilisent des crochets ; les parenthèses appelent une fonction.
    • Déclarer [1:5] puis parcourir 0 TO 4.
    8.2

    Tableaux bidimensionnels

    English

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

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

    Nested loops walk a table

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

    ⚠️ 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.
    Français

    Un tableau 2-D 二维数组 est un tableau : lignes et colonnes, deux index.

    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]
    

    Le premier index est la ligne 行, le second la colonne 列.

    Les boucles imbriquées parcourent un tableau

    Une boucle par dimension 维度. La boucle intérieure termine une ligne entière avant que l'extérieure ne passe à la suivante.

    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
    

    ⚠️ L'inner NEXT ferme le compteur intérieur. NEXT Row avant NEXT Col traverse les boucles et n'a aucun sens — un marqueur le remarque instantanément.

    Erreurs courantes

    • Inverser ligne et colonne. Grid[2,3] est ligne 2, colonne 3.
    • Grid[Row][Col]. Cambridge écrit une paire de crochets avec une virgule à l'intérieur.
    • Traverser les lignes NEXT comme ci-dessus.
  • 9 Procedures and functions · ⁨Procédures et fonctions⁩
    9.1

    PROCÉDURE et APPEL

    English

    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.

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

    • 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.
    Français

    Une procédure 过程 est un bloc nommé d'instructions. En écrire une une fois et l'appeler depuis plusieurs endroits est la décomposition 分解 — l'idée sur laquelle repose entièrement le papier 2.

    PROCEDURE <identifier>
        <statements>
    ENDPROCEDURE
    

    Une procédure est appelée par nom, avec le mot-clé CALL :

    PROCEDURE DefaultLine
        OUTPUT "------------------------------"
    ENDPROCEDURE
    
    CALL DefaultLine
    OUTPUT "Report"
    CALL DefaultLine
    
    • La définition 定义 ne fait rien toute seule. Seul CALL l'exécute.
    • Le contrôle retourne à la ligne suivant l'appel CALL lorsque la procédure se termine.
    • Une procédure ne renvoie pas de valeur. Si vous en avez besoin, vous voulez une fonction.

    Erreurs courantes

    • Écrire DefaultLine seul pour l'exécuter. 0478 exige CALL.
    • Omettre ENDPROCEDURE.
    • S'attendre à ce que les variables propres à la procédure existent à l'extérieur.
    9.2

    FONCTION et RETOUR

    English

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

    • 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 function inside a condition

    Common mistakes

    • CALL SumSquare(10, 20) — that throws the answer away.
    • A function with no RETURN on some path. Every route out must return a value.
    • Leaving RETURNS INTEGER off the header.
    Français

    Une fonction 函数 est une procédure qui rend une valeur. Elle s'écrit là où cette valeur est nécessaire — à l'intérieur d'un OUTPUT, à droite d'une affectation, dans une 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> dans l'en-tête indique quel type est rendu. Ce n'est pas optionnel.
    • RETURN termine la fonction immédiatement — rien après ne s'exécute.
    • Une fonction n'est jamais appelée avec CALL ; elle est utilisée partout où sa valeur est requise.

    Une fonction dans une 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
    

    Erreurs courantes

    • CALL SumSquare(10, 20) — qui jette la réponse.
    • Une fonction sans RETURN sur certains chemins. Chaque sortie doit retourner une valeur.
    • Omettre RETURNS INTEGER de l'en-tête.
    9.3

    Paramètres

    English

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

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

    ⚠️ 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.)

    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.
    Français

    Un paramètre 参数 est une valeur qu'une procédure ou une fonction reçoit lors de son appel. Chacun portent son propre type.

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

    Plusieurs paramètres sont séparés par des virgules, et l'ordre à l'appel doit correspondre à l'ordre dans la définition :

    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)
    

    ⚠️ Dans 0478 tous les paramètres sont passés par valeur 传值 : la procédure travaille sur une copie, donc la modifier à l'intérieur ne change rien à l'extérieur. Pour obtenir une valeur de retour, utilisez une FUNCTION et RETURN la. (A-Level 9618 ajoute BYREF pour l'autre comportement — sujet 11.)

    FUNCTION Doubled(Number : INTEGER) RETURNS INTEGER
        RETURN Number * 2
    ENDFUNCTION
    
    DECLARE Value : INTEGER
    Value ← 7
    Value ← Doubled(Value)
    OUTPUT Value
    

    Erreurs courantes

    • PROCEDURE Line(Size) sans type.
    • Appeler avec les arguments dans le mauvais ordre — Greet(2, "Mei") est une erreur de type.
    • S'attendre à ce qu'une procédure modifie la variable que vous avez passée. En 0478, elle ne peut pas.
  • 10 File handling · ⁨Gestion de fichiers⁩
    10.1

    Écrire dans un fichier

    English

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

    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
    • 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.

    Common mistakes

    • FOR WRITE when you meant FOR APPEND, which silently destroys the old contents.
    • Forgetting CLOSEFILE.
    • Opening a file that is already open.
    Français

    Un fichier 文件 conserve les données après la fin du programme. 0478 utilise quatre commandes, et chacune nomme le fichier sur lequel elle opère.

    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"
    

    Trois modes de fichier 文件模式 :

    Mode Ce qu'il fait
    WRITE créer un nouveau fichier — tout ce qui y était déjà est perdu
    APPEND ajouter à la fin de ce qui existe déjà 追加
    READ lire depuis le début
    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"
    
    • Un WRITEFILE écrit une ligne.
    • CLOSEFILE n'est pas optionnel. Un fichier non fermé peut perdre les données encore en attente d'être écrites, et c'est une réponse d'examen classique.

    Erreurs courantes

    • FOR WRITE au lieu de FOR APPEND, qui détruit silencieusement l'ancien contenu.
    • Oublier CLOSEFILE.
    • Ouvrir un fichier déjà ouvert.
    10.2

    Lire un fichier jusqu'à la fin

    English

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

    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.

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

    Counting while reading

    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 was never written.
    Français

    READFILE lit une ligne dans une variable. La variable doit être déclarée au préalable.

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

    Normalement, vous ne savez pas combien de lignes il y a, donc vous lisez jusqu'à la fin du fichier — ce que rapporte la fonction EOF.

    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") est TRUE une fois que toutes les lignes ont été lues, donc WHILE NOT EOF(...) signifie tant qu'il reste encore quelque chose à lire.

    Compter pendant la lecture

    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
    

    Erreurs courantes

    • Une boucle WHILE EOF(...) — qui ne s'exécute que lorsqu'il ne reste plus rien. Vous voulez NOT.
    • Lire au-delà de la fin car la boucle n'a pas de garde EOF.
    • Ouvrir FOR READ un fichier qui n'a jamais été écrit.
  • 11 A-Level 9618: what changes · ⁨A-Level 9618 : quels changements⁩
    11.1

    Mise en page et opérateurs

    English

    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

    This is the 0478 form, and it runs here:

    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:

    ⚠️ Which one is right depends only on which paper you are sitting. Neither is a mistake; each is a mistake in the other's exam. 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.
    Français

    Cambridge publie deux spécifications pseudocode, et elles divergent. Tout dans les chapitres 1-10 correspond à l'IGCSE 0478. L'A-Level 9618 modifie les détails ci-dessous — et un élève qui étudie les deux perd des points en écrivant l'un dans l'examen de l'autre.

    IGCSE 0478 A-Level 9618
    THEN sur sa propre ligne, indentée de 2 sur la même IF ligne
    constantes CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD fonctions : DIV(10, 3) opérateurs : 10 DIV 3
    concaténation de chaînes virgules dans OUTPUT l'opérateur &
    identifiants doivent commencer par une majuscule majuscules et minuscules autorisées 混合大小写
    NEXT doit nommer son compteur bonne pratique
    ROUND, RANDOM() tous deux publiés aucun n'existe

    Il s'agit du format 0478, et il s'exécute ici :

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

    Le format 9618 du même algorithme est écrit ainsi — notez THEN sur la IF ligne, = dans le CONSTANT, et MOD entre ses deux valeurs :

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

    ⚠️ Laquelle est correcte dépend uniquement de l'examen que vous passez. Aucune n'est une erreur; chacune est une erreur dans l'examen de l'autre. Le terrain de jeu de cette page exécute les règles 0478, ainsi une construction 9618 sera refusée avec un message indiquant le programme auquel elle appartient — qui est un moyen rapide de vérifier vos propres habitudes.

    Erreurs courantes

    • Écrire THEN sur la IF ligne dans une réponse 0478, parce que c'est ce qu'un manuel ou un site web a montré. C'est l'erreur inter-programmes la plus courante.
    • 10 MOD 3 en 0478. Là, c'est MOD(10, 3).
    • ROUND(3.14159, 2) dans une réponse 9618. Le 9618 n'a absolument pas de ROUND.
    11.2

    Paramètres : BYVAL et BYREF

    English

    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 引用, 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:

    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:

    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.
    Français

    Le 0478 passe tous les paramètres par valeur 传值 (chapitre 9). Le 9618 vous laisse choisir, et l'indique dans l'en-tête.

    • BYVAL — la procédure reçoit une copie. La modifier ne change rien à l'extérieur. C'est le défaut lorsque ni l'un ni l'autre mot n'est écrit.
    • BYREF — la procédure travaille sur la variable propriétaire 引用 de l'appelant, donc un changement est visible après l'appel.

    Ceci est uniquement pour le 9618. Il ne s'exécute pas ici, et n'est pas accepté dans une réponse 0478 :

    PROCEDURE Increase(BYREF Value : INTEGER)
        Value ← Value + 1
    ENDPROCEDURE
    
    DECLARE Count : INTEGER
    Count ← 5
    CALL Increase(Count)
    OUTPUT Count      // prints 6
    

    La façon 0478 d'obtenir une valeur en retour

    Utilisez une FUNCTION et affectez ce qu'elle retourne. C'est toute la réponse 0478, et elle s'exécute :

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

    Erreurs courantes

    • Écrire BYREF dans une réponse 0478. Ce mot-clé n'est pas dans ce programme.
    • S'attendre à ce qu'un paramètre 9618 standard se comporte comme une BYREF. Sans le mot, c'est BYVAL.
    11.3

    Enregistrements et autres types

    English

    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):

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

    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.
    Français

    Le 9618 possède des structures de données 数据结构 que le 0478 n'a pas. Vous les rencontrerez uniquement au niveau A-Level, et aucun ne s'exécute sous les règles 0478 de cette page.

    Un record 记录 regroupe des champs de types différents sous un seul nom (section 9618 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
    

    Un type énuméré 枚举类型 liste les seules valeurs qu'une variable peut prendre :

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

    Le 9618 ajoute également un type de données DATE, fichiers à accès aléatoire (OPENFILE … FOR RANDOM), pointeurs, et classes avec CLASS … ENDCLASS pour son examen orienté objet.

    ⚠️ Le 0478 a cinq types de données et les tableaux, et rien d'autre (chapitre 2). Une réponse 0478 qui déclare un enregistrement répond à un autre programme.

    Erreurs courantes

    • Utiliser un enregistrement dans une réponse 0478. Utilisez plutôt des tableaux parallèles — un tableau par champ, partageant un index.
    • Penser que TYPE signifie la même chose que DECLARE. TYPE définit un nouveau type ; DECLARE crée une variable d'un type existant.

Log in or create account · ⁨Se connecter ou créer un compte⁩

IGCSE, A-Level & AP