Skip to content · ⁨Saltar al contenido⁩
Subjects · ⁨Temas⁩
  • 1 Style and layout · ⁨Estilo y diseño⁩
    1.1

    Palabras clave y casos

    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.
    Español

    El pseudocódigo es el lenguaje en el que Cambridge escribe algoritmos. No es un lenguaje de programación real —ninguna computadora lo ejecuta—, pero en el examen se califica como si lo fuera, por lo que la forma importa.

    Toda palabra clave se escribe en mayúsculas: IF, REPEAT, PROCEDURE, OUTPUT.

    DECLARE Count : INTEGER
    Count ← 3
    IF Count > 0
      THEN
        OUTPUT "Ready"
    ENDIF
    
    • Escribe IF, nunca if o If.
    • Una palabra clave nunca puede usarse como nombre propio: no puedes llamar a una variable FOR.

    Errores comunes

    • Palabras clave en minúsculas. El esquema de corrección espera mayúsculas.
    • Inventar palabras clave. Solo las palabras incluidas en este material están en el programa oficial.
    1.2

    Identificadores

    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.
    Español

    Un identificador es el nombre que asignas a una variable, una constante, un procedimiento o una función.

    DECLARE NumberOfPlayers : INTEGER
    NumberOfPlayers ← 4
    OUTPUT NumberOfPlayers
    

    Cuatro reglas, todas extraídas del programa oficial:

    • Debe comenzar con una letra mayúscula: Count, no count.
    • Solo puede contener letras y dígitos; no se permiten espacios ni signos de puntuación.
    • No distingue entre mayúsculas y minúsculas (no es case-sensitive), por lo que Count y COUNT son el mismo nombre. Elige una ortografía y mantenla.
    • Que tenga significado. NumberOfPlayers facilita la lectura; N no.

    Errores comunes

    • count ← 0 — comienza con minúscula. La prueba 0478 requiere mayúscula inicial.
    • Number of players — no se permiten espacios dentro de un nombre.
    1.3

    Comentarios e indentación

    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.
    Español

    Un comentario comienza con // y continúa hasta el final de la línea. Es para el lector humano; el algoritmo lo ignora.

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

    La indentación muestra qué sentencias están dentro de una estructura. El programa oficial exige cuatro espacios por nivel, con una excepción que debes conocer:

    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 y ELSE tienen una indentación de dos espacios respecto a su IF.
    • Las sentencias debajo de ellos tienen una indentación de cuatro.
    • Las líneas ENDIF se alinean con su correspondiente IF.

    Errores comunes

    • Colocar THEN en la misma línea que IF. Ese es el formato de A-Level 9618; véase el tema 11.
    • Ausencia total de indentación. Un evaluador necesita distinguir la estructura para otorgar los puntos correspondientes.
  • 2 Variables, constants and types · ⁨Variables, constantes y tipos⁩
    2.1

    Los cinco tipos de datos

    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.
    Español

    El pseudocódigo 0478 tiene exactamente cinco tipos de datos. Aprende la lista: nombrar un tipo que no figure en ella implica la pérdida de puntos.

    Tipo Contiene Ejemplo
    INTEGER un número entero 整数 42, -7
    REAL un número con parte decimal 小数 3.14, -0.5
    CHAR un único carácter 单个字符 'A'
    STRING una secuencia de caracteres 字符串 "Hello"
    BOOLEAN TRUE o 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
    
    • Un STRING se escribe entre comillas dobles, mientras que un CHAR se escribe entre comillas simples.
    • TRUE y FALSE son palabras clave, por lo que van en mayúsculas y no llevan comillas.

    Errores comunes

    • Escribir FLOAT, DOUBLE o BOOL. Son lenguajes reales, pero no forman parte de este programa de estudios.
    • Usar 'Hello' para una cadena: las comillas simples solo contienen un carácter.
    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.
    Español

    La instrucción DECLARE nombra una variable 变量 y fija su tipo antes de utilizarla.

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

    Varios nombres del mismo tipo pueden ir en una sola línea, separados por comas:

    DECLARE Length, Width, Area : INTEGER
    Length ← 6
    Width ← 4
    Area ← Length * Width
    OUTPUT "Area = ", Area
    
    • Declara una variable antes de su primer uso, cerca del inicio del algoritmo.
    • Una variable mantiene su tipo durante todo el algoritmo — un INTEGER nunca contendrá "Mei".

    Errores comunes

    • Omisión de los dos puntos: DECLARE Counter INTEGER.
    • Uso de una variable que nunca fue declarada. El examen exige la declaración.
    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.
    Español

    Una constante 常量 es un valor fijo durante todo el algoritmo —como una tasa de impuestos, π o el tamaño de un grupo—. Nombrarla una sola vez significa que cualquier cambio se realiza en un único lugar.

    CONSTANT <identifier> ← <value>
    
    CONSTANT TaxRate ← 0.20
    DECLARE Price, Tax : REAL
    Price ← 50.00
    Tax ← Price * TaxRate
    OUTPUT "Tax to pay: ", Tax
    
    • En el 0478 se usa la flecha, exactamente igual que en una asignación.
    • El valor debe ser un literal 字面量 —un número, una cadena, TRUE—, nunca un cálculo ni otra variable.
    • A una constante nunca se le puede asignar un nuevo valor posteriormente. Ese es su propósito principal.

    Errores comunes

    • CONSTANT TaxRate = 0.20. La forma con = es la ortografía del A-Level 9618; consulta el tema 11.
    • Asignar un valor a una constante más adelante en el algoritmo.
  • 3 Assignment, input and output · ⁨Asignación, entrada y salida⁩
    3.1

    La flecha de asignación

    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.
    Español

    El operador de asignación 赋值 es ←, una flecha apuntando a la izquierda. Significa tomar el valor del lado derecho y colocarlo en la caja del lado izquierdo.

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

    Counter ← Counter + 1 parece imposible como matemática, pero es una instrucción ordinaria: calcular el lado derecho con el valor que actualmente contiene la caja, y luego almacenar el resultado de nuevo.

    • Si no puede escribir ←, escriba <-. Ambas son aceptadas aquí y en el examen.
    • El lado izquierdo debe ser un identificador único o un solo elemento de una matriz. Nunca una operación aritmética.

    Errores comunes

    • Counter = 0. En pseudocódigo, = es una comparación, no una asignación; confundirlos es el error de sintaxis más frecuente en este tema.
    • Counter + 1 ← Counter. La flecha apunta al elemento que se está modificando.
    3.2

    ENTRADA (INPUT) Y SALIDA (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.
    Español

    INPUT lee un valor del usuario y lo almacena en una variable. OUTPUT muestra uno o más valores.

    DECLARE Name : STRING
    DECLARE Age : INTEGER
    INPUT Name
    INPUT Age
    OUTPUT "Hello ", Name
    OUTPUT "Next year you will be ", Age + 1
    
    • INPUT toma exactamente una variable, y esa variable ya debe estar declarada.
    • OUTPUT acepta cualquier cantidad de elementos separados por comas; se imprimen uno tras otro sin nada entre ellos.
    • Una cadena literal 字面量 dentro de un OUTPUT va entre comillas dobles; una variable no.

    Solicitar datos al usuario

    Un INPUT solo no muestra nada en pantalla, por lo que un algoritmo bien escrito primero imprime una instrucción o indicación 提示:

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

    Errores comunes

    • INPUT "Enter a number", X — la indicación es una sentencia OUTPUT separada.
    • OUTPUT "Total: " + Total. 0478 une los elementos de salida con una coma; + es aritmético y & pertenece al A-Level 9618 (tema 11).
    • Olvidar las comillas: OUTPUT Hello busca una variable llamada Hello.
  • 4 Arithmetic and logic · ⁨Aritmética y lógica⁩
    4.1

    Operadores aritméticos

    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 /.
    Español

    Cinco operadores aritméticos, en el orden que usa una calculadora.

    Operador Significado A es 7, B es 2
    + sumar A + B es 9
    - restar A - B es 5
    * multiplicar A * B es 14
    / dividir A / B es 3.5
    ^ elevar a una potencia A ^ B es 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
    

    Los paréntesis van primero, luego ^, luego * y /, luego + y -: la precedencia habitual. Use paréntesis siempre que quien lea tenga que detenerse a pensar.

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

    Errores comunes

    • Esperar que / devuelva un número entero. 7 / 2 es 3.5, no 3; para obtener un número entero use DIV.
    • Escribir A x B o A ÷ B. Use * y /.
    4.2

    DIV y 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.
    Español

    La división entera responde a dos preguntas diferentes, y el programa 0478 escribe cada una como una función, con los dos valores entre corchetes.

    • DIV(a, b) — cuántas veces enteras cabe b en a, el cociente.
    • MOD(a, b) — qué sobra, el resto.
    OUTPUT DIV(10, 3)
    OUTPUT MOD(10, 3)
    OUTPUT DIV(17, 5)
    OUTPUT MOD(17, 5)
    

    Ambos toman enteros y ambos devuelven un entero.

    Para qué sirven

    MOD es la prueba estándar para dividir exactamente, lo que lo convierte en la forma de preguntar si un número es par:

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

    DIV convierte un total en unidades enteras: segundos a minutos, peniques a libras:

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

    Errores comunes

    • 10 MOD 3. Esa es la forma del A-Level 9618; el 0478 usa la forma de función MOD(10, 3).
    • Mezclarlos. DIV da la parte entera; MOD da lo que no cabe.
    4.3

    Operadores relacionales y lógicos

    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.
    Español

    Un operador relacional compara dos valores y produce TRUE (verdadero) o FALSE (falso).

    Operador Significa
    = es igual a
    <> no es igual a
    > es mayor que
    < es menor que
    >= es mayor o igual que
    <= es menor o igual que
    DECLARE Mark : INTEGER
    Mark ← 55
    OUTPUT "Pass: ", Mark >= 50
    OUTPUT "Perfect: ", Mark = 100
    OUTPUT "Not zero: ", Mark <> 0
    

    Los tres operadores lógicos unen condiciones:

    • AND — ambos lados deben ser TRUE.
    • OR — al menos un lado debe ser TRUE.
    • NOT — invierte TRUE a FALSE y viceversa.
    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
    

    Errores comunes

    • <> es aquí el signo de no igual — no !=, que pertenece a otros lenguajes.
    • IF Age >= 15 AND <= 18. Cada lado de AND necesita su propia comparación completa: Age >= 15 AND Age <= 18.
    • Llamar a estos operadores de comparación en una respuesta. El término del programa de estudios es relacionales.
  • 5 String operations · ⁨Operaciones con cadenas⁩
    5.1

    LONGITUD, UCASE y 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.
    Español

    0478 publica cuatro rutinas de cadenas de texto y ninguna otra. Tres de ellas se muestran aquí.

    LENGTH(<identifier>) devuelve cuántos caracteres contiene una cadena —incluyendo los espacios—.

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

    UCASE(<identifier>) devuelve la cadena en mayúsculas, LCASE(<identifier>) en minúsculas. Ninguna modifica el valor original —cada una devuelve un nuevo valor—.

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

    Esa última línea sigue imprimiendo Happy: para guardar el cambio, debes asignarlo de vuelta.

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

    Comparar sin preocuparse por las mayúsculas o minúsculas

    UCASE en ambos lados es la forma estándar de aceptar una respuesta sin importar cómo fue escrita:

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

    Errores comunes

    • Esperar que UCASE(Name) cambie Name. Asigna el resultado de vuelta.
    • LENGTH cuenta caracteres, no palabras. LENGTH("Happy Days") es 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.
    Español

    SUBSTRING(<identifier>, <start>, <length>) extrae una parte de una cadena —comenzando en la posición start, tomando length caracteres—.

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

    ⚠️ El conteo comienza en 1, no en 0. El primer carácter de "Happy Days" está en la posición 1.

    Tomar un solo carácter y el resto

    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 dentro de SUBSTRING es lo que hace que las últimas dos líneas funcionen para una palabra de cualquier tamaño —fijar 8 rompería todo en cuanto cambiara la palabra—.

    Leer una cadena un carácter a la vez

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

    Errores comunes

    • Empezar en 0. La posición 1 es el primer carácter.
    • Leer el tercer argumento como una posición final. Es un recuento —SUBSTRING(W, 2, 3) toma tres caracteres comenzando desde el segundo.
    • Pedir más caracteres de los que tiene la cadena.
  • 6 Selection · ⁨Selección⁩
    6.1

    SI, ENTONCES, SINO, 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.
    Español

    Selección 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
    

    Añade ELSE para el otro caso. Exactamente una de las dos ramas 分支 se ejecuta — nunca ambas, nunca ninguna.

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

    El formato es la parte en la que los estudiantes pierden puntos, así que apréndelo como una forma:

    • IF y su condición en una sola línea, nada después de la condición.
    • THEN y ELSE en sus propias líneas, indentados dos espacios.
    • Las instrucciones indentadas cuatro.
    • ENDIF vuelve a la columna de su IF.

    Anidamiento 嵌套

    Un IF dentro de un IF maneja más de dos resultados. Cada uno necesita su propio ENDIF.

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

    Errores comunes

    • Olvidar ENDIF. Cada IF se cierra, y uno faltante es un error de sintaxis 语法错误 que el marcador verá de un vistazo.
    • IF Mark >= 50 THEN OUTPUT "Pass" en una sola línea. No existe tal forma en ninguno de los programas; escribe las tres líneas.
    • IF Mark = 50 THEN escrito como IF Mark ← 50. La flecha asigna; = compara.
    6.2

    CASO 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.
    Español

    Cuando se prueba una variable contra varios valores únicos, CASE OF lo dice mucho más claramente que una pila de IF anidados.

    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
    
    • Cada rama es un valor, dos puntos, luego qué hacer.
    • OTHERWISE captura todo lo que los valores enumerados dejaron pasar. Es opcional, y escribirlo es buena práctica — es lo que sucede cuando el usuario introduce algo inesperado.
    • Se ejecuta la primera rama coincidente, y el resto se omite.

    Un rango y un carácter

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

    Errores comunes

    • Usar CASE OF para una condición. Prueba una variable contra valores; Mark >= 50 necesita un IF.
    • Olvidar ENDCASE.
    • Dejar fuera OTHERWISE y luego preguntarse por qué un valor inesperado no hace nada en absoluto.
  • 7 Iteration · ⁨Iteración⁩
    7.1

    FOR, el bucle con contador

    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.
    Español

    Iteración 迭代 repite instrucciones. Utilice un bucle FOR cuando sepa antes de comenzar cuántas veces debe repetirse — es un bucle controlado por conteo 计数控制.

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

    El contador 计数器 comienza en el primer valor, y el bucle se ejecuta una vez por cada valor hasta incluyendo el segundo. 1 TO 5 se ejecuta cinco veces.

    STEP

    STEP cambia el tamaño de cada salto. Un paso negativo cuenta hacia atrás.

    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
    

    Sumas acumuladas

    El uso más común: una variable fuera del bucle a la que el bucle va sumando valores.

    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 debe estar antes del bucle. Si se colocara dentro, se reiniciaría en cada vuelta.

    Errores comunes

    • Escribir NEXT con el nombre incorrecto del contador. Los bucles anidados deben cerrarse en orden inverso al que se abrieron: primero el NEXT interno.
    • Asumir que 1 TO 5 se ejecuta cuatro veces. Ambos extremos están incluidos.
    • Modificar el contador dentro del bucle. Deje que FOR lo gestione.
    7.2

    WHILE, el bucle de precondición

    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.
    Español

    Un bucle WHILE verifica la condición antes de cada iteración, por lo que puede ejecutarse cero veces. Úselo cuando el número de repeticiones dependa de algo que ocurre durante la ejecución del bucle.

    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
    

    Algo dentro del bucle debe hacer que la condición termine siendo falsa; de lo contrario, el bucle nunca termina — es un bucle infinito 无限循环.

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

    Errores comunes

    • Olvidar modificar la variable que evalúa la condición, provocando un bucle infinito.
    • Omidir DO o ENDWHILE.
    • Usar WHILE cuando el número de repeticiones es conocido. Un FOR expresa la intención en una sola línea.
    7.3

    REPEAT, el bucle de postcondición

    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.
    Español

    Un bucle REPEAT verifica la condición después de cada iteración, por lo que siempre se ejecuta al menos una vez.

    REPEAT
        <statements>
    UNTIL <condition>
    

    Ese "al menos una vez" es la razón para elegirlo: para validar 验证 entrada, donde debe preguntar antes de poder juzgar la respuesta.

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

    ⚠️ UNTIL establece la condición que detiene el bucle; WHILE establece la que mantiene su ejecución. Son opuestas, e intercambiarlas es el error clásico.

    Verifica ¿Se ejecuta al menos una vez? Significado de la condición
    FOR un contador no (un rango vacío se ejecuta cero veces) —
    WHILE antes no continuar mientras esto sea verdadero
    REPEAT después sí detenerse cuando esto se vuelva verdadero

    Errores comunes

    • Escribir UNTIL Number < 100 cuando meant decir UNTIL Number >= 100.
    • Usar REPEAT cuando el cuerpo del bucle podría necesitar ejecutarse cero veces.
    • Olvidar que UNTIL cierra la estructura — no existe ENDREPEAT.
  • 8 Arrays · ⁨Arreglos⁩
    8.1

    Arreglos unidimensionales

    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.
    Español

    Un arreglo 数组 contiene muchos valores de un mismo tipo bajo un solo nombre. Cada valor se ubica en un índice 下标.

    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]
    
    • Los límites 边界 se escriben lower:upper, y ambos están incluidos — [1:3] tiene tres elementos 元素.
    • Los arreglos de Cambridge comienzan normalmente en 1, no en 0.
    • Todos los elementos tienen el mismo tipo, definido por OF.

    Llenado y lectura con un bucle FOR

    Un arreglo y un bucle numerado van juntos: el contador es el índice.

    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
    

    Encontrar el valor más grande

    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
    

    Inicia Largest en el primer elemento, nunca en 0 — con datos negativos, 0 ganaría y la respuesta sería incorrecta.

    Errores comunes

    • Leer Scores[6] de un arreglo declarado [1:5]. Eso está fuera de límites 越界.
    • Escribir Scores(3). Los arreglos usan corchetes; los paréntesis llaman a una función.
    • Declarar [1:5] y luego iterar 0 TO 4.
    8.2

    Arreglos bidimensionales

    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.
    Español

    Un arreglo 2-D 二维数组 es una tabla: filas y columnas, dos índices.

    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]
    

    El primer índice es la fila 行, el segundo la columna 列.

    Buces anidados recorren una tabla

    Un bucle por dimensión 维度. El bucle interno termina toda una fila antes de que el externo avance.

    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
    

    ⚠️ El NEXT interno cierra el contador interno. NEXT Row antes de que NEXT Col cruce los bucles y sea sin sentido — un marcador lo detecta al instante.

    Errores comunes

    • Intercambiar fila y columna. Grid[2,3] es fila 2, columna 3.
    • Grid[Row][Col]. Cambridge escribe un par de corchetes con una coma adentro.
    • Cruzar las líneas de NEXT, como se mostró arriba.
  • 9 Procedures and functions · ⁨Procedimientos y funciones⁩
    9.1

    PROCEDIMIENTO Y LLAMADA

    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.
    Español

    Un procedimiento 过程 es un bloque nombrado de sentencias. Escribirlo una vez y llamarlo desde varios lugares es descomposición 分解 — la idea sobre la que descansa el Paper 2 entero.

    PROCEDURE <identifier>
        <statements>
    ENDPROCEDURE
    

    Un procedimiento se llama por su nombre, con la palabra clave CALL:

    PROCEDURE DefaultLine
        OUTPUT "------------------------------"
    ENDPROCEDURE
    
    CALL DefaultLine
    OUTPUT "Report"
    CALL DefaultLine
    
    • La definición 定义 no hace nada por sí sola. Solo CALL lo ejecuta.
    • El control vuelve a la línea posterior al CALL cuando termina el procedimiento.
    • Un procedimiento no devuelve un valor. Si necesitas uno, debes usar una función.

    Errores comunes

    • Escribir DefaultLine solo para ejecutarlo. En 0478 se requiere CALL.
    • Omisión del ENDPROCEDURE.
    • Esperar que las variables propias del procedimiento existan fuera de él.
    9.2

    FUNCIÓN Y DEVOLUCIÓN

    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.
    Español

    Una función 函数 es un procedimiento que devuelve un valor. Se escribe donde ese valor sea necesario — dentro de un OUTPUT, a la derecha de una asignación, dentro de una condición.

    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)
    
    • El RETURNS <data type> en el encabezado indica qué tipo se devuelve. No es opcional.
    • El RETURN finaliza la función inmediatamente; nada posterior se ejecuta.
    • Una función nunca se llama con CALL; se usa donde corresponda su valor.

    Una función dentro de una condición

    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
    

    Errores comunes

    • ️ CALL SumSquare(10, 20) — eso desecha la respuesta.
    • Una función sin un RETURN en algún camino. Cada ruta de salida debe devolver un valor.
    • Dejar fuera el RETURNS INTEGER del encabezado.
    9.3

    Parámetros

    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.
    Español

    Un parámetro 参数 es un valor que recibe un procedimiento o función cuando se le llama. Cada uno tiene su propio tipo.

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

    Varios parámetros se separan con comas, y el orden en la llamada debe coincidir con el orden en la definición:

    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)
    

    ⚠️ En 0478 cada parámetro se pasa por valor 传值: el procedimiento trabaja sobre una copia, por lo que modificarla internamente no cambia nada externamente. Para obtener un valor de vuelta, utiliza una FUNCTION y RETURN (A-Level 9618 añade BYREF para el otro comportamiento — tema 11).

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

    Errores comunes

    • ⚠️ PROCEDURE Line(Size) sin tipo.
    • Llamar con los argumentos en orden incorrecto — Greet(2, "Mei") es un error de tipo.
    • Esperar que un procedimiento modifique la variable que pasaste. En 0478 no puede hacerlo.
  • 10 File handling · ⁨Manejo de archivos⁩
    10.1

    Escritura en un archivo

    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.
    Español

    Un archivo 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 iniciar un nuevo archivo — cualquier cosa que haya allí se perderá
    APPEND añadir al final de lo que ya existe 追加
    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 no es opcional. Un archivo sin cerrar puede perder los datos que aún están esperando ser escritos, y esa es una respuesta típica de examen.

    Errores comunes

    • FOR WRITE cuando querías decir FOR APPEND, lo cual destruye silenciosamente el contenido anterior.
    • Forgetting CLOSEFILE.
    • Opening a file that is already open.
    10.2

    Leer un archivo hasta el final

    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.
    Español

    READFILE toma una línea y la asigna a una variable. La variable debe declararse primero.

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

    Normalmente no sabes cuántas líneas hay, por lo que lees hasta el final del 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") es TRUE una vez que se ha leído cada línea, por lo que WHILE NOT EOF(...) significa while there is still something to read.

    Contar mientras se lee

    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
    

    Errores comunes

    • Un bucle WHILE EOF(...) — que solo se ejecuta cuando no queda nada. Quieres NOT.
    • Leer más allá del final porque el bucle no tiene guardia EOF.
    • Opening FOR READ a file that was never written.
  • 11 A-Level 9618: what changes · ⁨A-Level 9618: qué cambios⁩
    11.1

    Estructura y operadores

    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.
    Español

    Cambridge publica dos especificaciones de pseudocódigo, y estas difieren. Todo en los temas 1-10 corresponde al IGCSE 0478. El A-Level 9618 cambia los detalles a continuación — y un estudiante que estudia ambos pierde marcas al escribir uno en el examen del otro.

    IGCSE 0478 A-Level 9618
    THEN en su propia línea, indentado 2 espacios en la misma línea del IF
    constantes CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD funciones: DIV(10, 3) operadores: 10 DIV 3
    unión de cadenas comas en OUTPUT el operador &
    identificadores deben comenzar con mayúscula se permite mezcla de mayúsculas y minúsculas 混合大小写
    NEXT debe nombrar su contador buena práctica
    ROUND, RANDOM() ambos están publicados ninguno existe

    Esta es la forma 0478, y funciona aquí:

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

    La forma 9618 del mismo algoritmo se escribe así — observe THEN en la línea IF, = en CONSTANT, y MOD entre sus dos valores:

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

    ⚠️ Cuál es correcta depende únicamente del examen que esté realizando. Ninguna es un error; cada una sería un error en el examen del otro. El simulador en esta página ejecuta las reglas 0478, por lo que una construcción 9618 será rechazada con un mensaje indicando a qué programa pertenece — lo cual es una forma rápida de verificar sus propios hábitos.

    Errores comunes

    • Escribir THEN en la línea IF en una respuesta 0478, porque eso es lo que mostró un libro de texto o una web. Es el error cruzado más frecuente entre programas.
    • Usar 10 MOD 3 en 0478. En este programa debe ser MOD(10, 3).
    • Usar ROUND(3.14159, 2) en una respuesta 9618. El 9618 no tiene ROUND en absoluto.
    11.2

    Parámetros: BYVAL y 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.
    Español

    El 0478 pasa todos los parámetros por valor 传值 (tema 9). El 9618 le permite elegir, y lo indica en el encabezado.

    • BYVAL — el procedimiento recibe una copia. Modificarla no cambia nada fuera de él. Este es el valor predeterminado cuando no se escribe ninguna de las dos palabras.
    • BYREF — el procedimiento trabaja sobre la variable 引用 original del llamador, por lo que cualquier cambio es visible después de la llamada.

    Esto es solo para el 9618. No funciona aquí, y no se acepta en una respuesta 0478:

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

    La forma 0478 de obtener un valor de vuelta

    Use una FUNCTION y asigne lo que devuelve. Esta es toda la respuesta 0478, y funciona:

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

    Errores comunes

    • Escribir BYREF en una respuesta 0478. Esta palabra clave no está en ese programa.
    • Esperar que un parámetro simple del 9618 se comporte como BYREF. Sin la palabra, es BYVAL.
    11.3

    Registros y otros tipos

    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.
    Español

    El 9618 tiene estructuras de datos 数据结构 que el 0478 no posee. Las encontrará solo en el A-Level, y ninguna funciona bajo las reglas 0478 de esta página.

    Un registro 记录 agrupa campos de diferentes tipos bajo un mismo nombre (sección 4 del 9618):

    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 tipo enumerado 枚举类型 lista los únicos valores que puede tomar una variable:

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

    El 9618 también añade un tipo de dato DATE, archivos de acceso aleatorio (OPENFILE … FOR RANDOM), punteros y clases con CLASS … ENDCLASS para su examen orientado a objetos.

    ⚠️ El 0478 tiene cinco tipos de datos y arrays, y nada más (tema 2). Una respuesta 0478 que declare un registro está respondiendo a un programa diferente.

    Errores comunes

    • Usar un registro en una respuesta 0478. Use en su lugar arrays paralelos — un array por campo, compartiendo un índice.
    • Pensar que TYPE significa lo mismo que DECLARE. TYPE define un nuevo tipo; DECLARE crea una variable de uno existente.

Log in or create account · ⁨Iniciar sesión o crear cuenta⁩

IGCSE, A-Level & AP