Programming basics · Conceptos básicos de programación
| English | Español |
|---|---|
| variable/ˈveərɪəbl/ | variable |
| data type/ˈdeɪtə taɪp/ | tipo de dato |
| constant/ˈkɒnstənt/ | constante |
| flowchart/ˈfləʊtʃɑːt/ | diagrama de flujo |
| structured English/ˈstrʌktʃəd ˈɪŋɡlɪʃ/ | inglés estructurado |
| pseudocode/ˈsuːdəʊkəʊd/ | pseudocódigo |
| assignment/əˈsaɪnmənt/ | asignación |
| identifier/aɪˈdentɪfaɪə/ | identificador |
| operators/ˈɒpəreɪtəz/ | operadores |
| precedence/ˈpresɪdəns/ | precedencia |
| concatenation/kənˌkætəˈneɪʃn/ | concatenación |
| library routines/ˈlaɪbrəri ruːˈtiːnz/ | rutinas de biblioteca |
| program library/ˈprəʊɡræm ˈlaɪbrəri/ | biblioteca de programas |
| insert/ˈɪnsɜːt/ | insert |
The number that did not fit
- On 4 June 1996 the first Ariane 5 rocket veered off course and destroyed itself 37 seconds after launch, with four satellites on board.
- The cause was one conversion: a 64-bit decimal value describing the rocket's sideways speed was copied into a 16-bit integer. Ariane 5 was faster than Ariane 4, the number was too big for the box, and the guidance computer shut down.
- Every variable has a data type 数据类型, and the type decides what fits. Choosing it is the first job in turning a design into code.
- This lesson is the basics: constants, variables, types, expressions, input and output, and the ready-made routines you may call.
El número que no encajaba
- El 4 de junio de 1996, el primer cohete Ariane 5 se desvió de su trayectoria y se autodestruyó 37 segundos después del lanzamiento, con cuatro satélites a bordo.
- La causa fue una conversión: un valor decimal de 64 bits que describía la velocidad lateral del cohete se copió en un entero de 16 bits. El Ariane 5 era más rápido que el Ariane 4, el número era demasiado grande para el contenedor y la computadora de guía se apagó.
- Cada variable tiene un tipo de dato 数据类型, y el tipo decide qué cabe dentro. Elegirlo es la primera tarea al convertir un diseño en código.
- Esta lección trata los fundamentos: constantes, variables, tipos, expresiones, entrada y salida, y las rutinas predefinidas que puedes llamar.
From design to code
- A design arrives as a flowchart 流程图 or as structured English 结构化英语. You turn it into pseudocode 伪代码, and later into a real language.
- Find the variables 变量 and their types. Input and output boxes become
INPUTandOUTPUT; decision diamonds becomeIF … ELSE … ENDIForCASE; loop arrows becomeWHILE,REPEAT … UNTILorFOR; process boxes become assignments. - Check by tracing a small input through your pseudocode before you call it finished.
Each flowchart symbol becomes one kind of pseudocode statement
Del diseño al código
- Un diseño llega como un diagrama de flujo 流程图 o como inglés estructurado 结构化英语. Lo conviertes en pseudocódigo 伪代码, y más tarde en un lenguaje real.
- Encuentra las variables 变量 y sus tipos. Las cajas de entrada y salida se convierten en
INPUTyOUTPUT; los rombos de decisión se convierten enIF … ELSE … ENDIFoCASE; las flechas de bucle se convierten enWHILE,REPEAT … UNTILoFOR; las cajas de proceso se convierten en asignaciones. - Verifica trazando una pequeña entrada a través de tu pseudocódigo antes de considerarlo terminado.

Cada símbolo de diagrama de flujo se convierte en un tipo de sentencia de pseudocódigo
Constants and variables
- A constant 常量 holds a value that never changes while the program runs:
CONSTANT Pi = 3.14159. A variable holds one that may change, and is declared with a type:DECLARE Radius : REAL. - Use a constant for a fixed value that appears in several places, such as a tax rate or a maximum score.
- The benefits the mark scheme lists: it is set once and cannot be changed accidentally; a change is made in one place and reaches every statement that uses it; the identifier 标识符 gives the value a meaningful name.
A variable can be reassigned; a constant cannot
Constantes y variables
- Una constante 常量 retiene un valor que nunca cambia mientras el programa se ejecuta:
CONSTANT Pi = 3.14159. Una variable retiene uno que puede cambiar, y se declara con un tipo:DECLARE Radius : REAL. - Usa una constante para un valor fijo que aparece en varios lugares, como una tasa de impuestos o una puntuación máxima.
- Los beneficios que lista la rúbrica de calificación: se establece una sola vez y no puede cambiarse accidentalmente; un cambio se realiza en un solo lugar y afecta a todas las sentencias que lo utilizan; el identificador 标识符 le da a la ruta un nombre significativo.

Una variable puede reasignarse; una constante no puede
A variable is a labelled box · Una variable es una caja etiquetada
Each assignment stores one value in a named box; reassigning the same name overwrites it. Step through the program and watch each box take its current value. · Cada asignación almacena un valor en una caja con nombre; reasignar el mismo nombre lo sobrescribe. Recorra el programa y observe cómo cada caja toma su valor actual.
A constant holds a fixed value that never changes while the program runs, whereas a variable can be reassigned. · Una constante mantiene un valor fijo que nunca cambia mientras se ejecuta el programa, mientras que una variable puede ser reasignada.
Constants (like Pi or a maximum score) make code clearer and let you change a recurring value in one place. · Las constantes (como Pi o una puntuación máxima) hacen que el código sea más claro y permiten cambiar un valor recurrente en un solo lugar.
Which are benefits of using a constant for a value such as a tax rate? Select all · todos that apply. · ¿Cuáles son los beneficios de usar una constante para un valor como una tasa de impuestos? Seleccione todos los que correspondan.
The three mark-scheme benefits are safety, a single point of change, and readability. Speed is not one of them. · Los tres beneficios del criterio de evaluación son seguridad, un único punto de cambio y legibilidad. La velocidad no es uno de ellos.
The six data types
INTEGERfor whole numbers (a count, an index, a loop counter).REALfor numbers with a fractional part (a price, an average).CHARfor one character in single quotes,'A'.STRINGfor text in double quotes,"Hello".BOOLEANforTRUEorFALSE(a flag such asFound).DATEfor a calendar date.- Read the type off how the variable is used: a decimal point means
REAL,TRUEmeansBOOLEAN, single quotes meanCHAR, an array index orDIVandMODmeanINTEGER. Write the type in capitals as the guide spells it.
Los seis tipos de datos
INTEGERpara números enteros (una cuenta, un índice, un contador de bucle).REALpara números con parte fraccionaria (un precio, un promedio).CHARpara un solo carácter entre comillas simples,'A'.STRINGpara texto entre comillas dobles,"Hello".BOOLEANparaTRUEoFALSE(una bandera tal comoFound).DATEpara una fecha calendar.- Lee el tipo según cómo se usa la variable: un punto decimal significa
REAL,TRUEsignificaBOOLEAN, comillas simples significanCHAR, un índice de matriz oDIVyMODsignificanINTEGER. Escribe el tipo en mayúsculas tal como lo especifica la guía.
Worked example: state the appropriate data type
Found ← FALSEisBOOLEAN: it holds a truth value.Initial ← 'K'isCHAR: one character in single quotes.Name ← "Li Wei"isSTRING: text in double quotes.Price ← 12.99isREAL: it has a fractional part.Count ← Count + 1isINTEGER: a counter that goes up in whole steps.- One mark per correct type, so answer every row even when unsure; a blank cannot score.
Ejemplo resuelto: indica el tipo de dato adecuado
Found ← FALSEesBOOLEAN: retiene un valor de verdad.Initial ← 'K'esCHAR: un carácter entre comillas simples.Name ← "Li Wei"esSTRING: texto entre comillas dobles.Price ← 12.99esREAL: tiene una parte fraccionaria.Count ← Count + 1esINTEGER: un contador que aumenta en pasos enteros.- Un punto por cada tipo correcto, así que responde cada fila incluso cuando estés inseguro; un espacio en blanco no otorga puntos.
Match each value to the data type its variable should be declared with. · Asocie cada valor con el tipo de dato con el que debe declararse su variable.
A decimal point, single quotes, double quotes and a truth value each point to one type. · Un punto decimal, comillas simples, comillas dobles y un valor de verdad apuntan cada uno a un tipo.
Assignment and expressions
- Assignment 赋值 uses the arrow:
Total ← Total + 1,Average ← Sum / Count. - Arithmetic operators 运算符 are
+ - * /, plusDIVfor whole-number division andMODfor the remainder:7 DIV 2 = 3and7 MOD 2 = 1. - Comparisons are
=,<>,<,>,<=,>=; logic isAND,OR,NOT. - Precedence 优先级, highest first:
NOT, then* / DIV MOD, then+ -, then comparisons, thenAND, thenOR. Use brackets when unsure.
Asignación y expresiones
- La asignación 赋值 usa la flecha:
Total ← Total + 1,Average ← Sum / Count. - Los operadores 运算符 aritméticos son
+ - * /, además deDIVpara división de números enteros yMODpara el resto:7 DIV 2 = 3y7 MOD 2 = 1. - Las comparaciones son
=,<>,<,>,<=,>=; la lógica esAND,OR,NOT. - La precedencia 优先级, de mayor a menor:
NOT, luego* / DIV MOD, luego+ -, luego comparaciones, luegoAND, luegoOR. Usa paréntesis cuando estés inseguro.
What is the value of 7 DIV 2? · ¿Cuál es el valor de 7 DIV 2?
DIV is integer division: 7 ÷ 2 = 3 remainder 1, so DIV gives 3. · DIV es división entera: 7 ÷ 2 = 3余数 1, así que DIV da 3.
What is the value of 7 MOD 2? · ¿Cuál es el valor de 7 MOD 2?
MOD gives the remainder: 7 ÷ 2 leaves remainder 1. · MOD da el residuo: 7 ÷ 2 deja residuo 1.
Which symbol assigns a value to a variable in this pseudocode? · ¿Qué símbolo asigna un valor a una variable en este pseudocódigo?
Assignment uses ←; = is comparison. · La asignación usa ←; = es comparación.
Match each pseudocode operator to what it does. · Asocie cada operador de pseudocódigo con lo que hace.
← stores, = compares; DIV gives the quotient and MOD the remainder (7 DIV 2 = 3, 7 MOD 2 = 1). · ← almacena, = compara; DIV da el cociente y MOD el residuo (7 DIV 2 = 3, 7 MOD 2 = 1).
Input and output
OUTPUT "Enter your name:"prompts;INPUT Namereads the keyboard into the variable;OUTPUT "Hello, ", Nameprints several items separated by commas.- Strings are joined with
&, called concatenation 拼接:"A" & "BC"is"ABC". - Keep the quotes straight:
"7"is a string,7is a number, and'7'is a single character.
Entrada y salida
OUTPUT "Enter your name:"presenta un mensaje;INPUT Namelee el teclado hacia la variable;OUTPUT "Hello, ", Nameimprime varios elementos separados por comas.- Las cadenas se unen con
&, llamado concatenación 拼接:"A" & "BC"es"ABC". - Mantén las comillas claras:
"7"es una cadena,7es un número, y'7'es un solo carácter.
Built-in functions and library routines
- A program library 程序库 holds routines that are already written, compiled and tested; calling one is faster and safer than writing your own. The Paper 2 insert 附页 lists the library routines 库例程 you may use, with their exact names.
- Strings:
LENGTH(s),LEFT(s, n),RIGHT(s, n),MID(s, start, n)with positions counted from 1,TO_UPPER(s),TO_LOWER(s). Conversion:NUM_TO_STR(x),STR_TO_NUM(s),IS_NUM(s),ASC(c),CHR(n). - Numbers and dates:
INT(x)cuts to the whole part;RAND(n)gives a real from 0 up to but not including n, soINT(RAND(6)) + 1is a dice roll;DAY,MONTH,YEAR,DAYINDEX,SETDATE,TODAY;EOF(f)for files.
The common string routines on s = "COMPUTER", positions 1 to 8
Funciones integradas y rutinas de biblioteca
- Una biblioteca de programas 程序库 contiene rutinas que ya están escritas, compiladas y probadas; llamar a una es más rápido y seguro que escribir la tuya propia. La inserta 附页 del Paper 2 lista las rutinas de biblioteca 库例程 que puedes usar, con sus nombres exactos.
- Cadenas:
LENGTH(s),LEFT(s, n),RIGHT(s, n),MID(s, start, n)con posiciones contadas desde 1,TO_UPPER(s),TO_LOWER(s). Conversión:NUM_TO_STR(x),STR_TO_NUM(s),IS_NUM(s),ASC(c),CHR(n). - Números y fechas:
INT(x)corta hasta la parte entera;RAND(n)da un real desde 0 hasta pero sin incluir n, así queINT(RAND(6)) + 1es un tiro de dado;DAY,MONTH,YEAR,DAYINDEX,SETDATE,TODAY;EOF(f)para archivos.

Las rutinas comunes de cadena en s = "COMPUTER", posiciones 1 a 8
Which routine converts a string to capitals in 9618 pseudocode? · ¿Qué rutina convierte una cadena a mayúsculas en el pseudocódigo 9618?
UCASE is the IGCSE name and is not accepted here. Use the exact names printed in the Paper 2 insert. · UCASE es el nombre IGCSE y no se acepta aquí. Use los nombres exactos impresos en la inserción del Paper 2.
Worked example: evaluate each expression
- Given
Word ← "Program",Code ← 'Q'andN ← 7. Work from the inside out. LENGTH(Word)is7.MID(Word, 4, 2)is"gr": two characters from position 4.LEFT(Word, 3) & "!"is"Pro!".TO_UPPER(RIGHT(Word, 2))is"AM": the inner function runs first.ASC(Code) - ASC('A')is16, because'Q'is 81 and'A'is 65.N DIV 2 + N MOD 2is3 + 1 = 4.NUM_TO_STR(N) & "th"is"7th".INT(N / 2)is3, the whole part of 3.5.
Ejemplo resuelto: evalúa cada expresión
- Dado
Word ← "Program",Code ← 'Q'yN ← 7. Trabaja de adentro hacia afuera. LENGTH(Word)es7.MID(Word, 4, 2)es"gr": dos caracteres desde la posición 4.LEFT(Word, 3) & "!"es"Pro!".TO_UPPER(RIGHT(Word, 2))es"AM": la función interna se ejecuta primero.ASC(Code) - ASC('A')es16, porque'Q'es 81 y'A'es 65.N DIV 2 + N MOD 2es3 + 1 = 4.NUM_TO_STR(N) & "th"es"7th".INT(N / 2)es3, la parte entera de 3.5.
With Word ← "Program", the value of MID(Word, 4, 2) is "". · Con Word ← "Program", el valor de MID(Word, 4, 2) es "".
Positions count from 1: P-r-o-g-r-a-m, so position 4 is g and two characters from there are gr. · Las posiciones se cuentan desde 1: P-r-o-g-r-a-m, así que la posición 4 es g y dos caracteres a partir de ahí son gr.
Worked example: find the error
- Each statement may misuse a function or an operator. Describe the error, or write NO ERROR.
Result ← 2 & 4:&joins strings, but 2 and 4 are integers, so+is needed.SubString ← MID("pseudocode", 4, 1): NO ERROR, one character from position 4,"u".Answer ← LENGTH(42):LENGTHtakes a string, not an integer.Flag ← "TRUE": a Boolean isTRUEwithout quotes; with quotes it is a string.
Ejemplo resuelto: encuentra el error
- Cada sentencia puede malutilizar una función u operador. Describe el error, o escribe NO ERROR.
Result ← 2 & 4:&une cadenas, pero 2 y 4 son enteros, por lo que se necesita+.SubString ← MID("pseudocode", 4, 1): NO ERROR, un carácter desde la posición 4,"u".Answer ← LENGTH(42):LENGTHtoma una cadena, no un entero.Flag ← "TRUE": un Booleano esTRUEsin comillas; con comillas es una cadena.
Result ← 2 & 4 correctly stores 6 in Result. · Result ← 2 & 4 almacena correctamente 6 en Result.
& joins strings. For two integers the operator is +; this is the error the exam asks you to describe. · & une cadenas. Para dos enteros el operador es +; este es el error que el examen le pide describir.
Marks that slip away
- The IGCSE names
UCASE,LCASE,VALandSTRare not accepted at A Level. UseTO_UPPER,TO_LOWER,STR_TO_NUM,NUM_TO_STR. - Single quotes make a
CHAR, double quotes make aSTRING.'A'and"A"are different types. - String positions start at 1, not 0.
MID(s, 1, 1)is the first character. RAND(n)never returns n itself, andINTcuts off the fraction rather than rounding.
Puntos que se pierden fácilmente
- IGCSE nombra
UCASE,LCASE,VALySTR, pero no son aceptados en A Level. UsaTO_UPPER,TO_LOWER,STR_TO_NUM,NUM_TO_STR. - Las comillas simples forman un
CHAR, las dobles forman unSTRING.'A'y"A"son tipos diferentes. - Las posiciones de las cadenas comienzan en 1, no en 0.
MID(s, 1, 1)es el primer carácter. RAND(n)nunca devuelve n mismo, eINTrecorta la fracción en lugar de redondear.
You've got it
- design → pseudocode: find the variables and types, then map each flowchart symbol to a statement and trace a small input
- constant set once, changed in one place, named; variable declared with one of six types read off how it is used
←assigns;DIVwhole-number division,MODremainder; precedenceNOT→* / DIV MOD→+ -→ comparisons →AND→OR- use the insert's library routines with their exact 9618 names:
LENGTH,MID,TO_UPPER,NUM_TO_STR,INT,RAND
Ya lo dominas
- diseño → pseudocódigo: encuentra las variables y tipos, luego mapea cada símbolo de diagrama de flujo a una sentencia y traza una entrada pequeña
- constante establecida una vez, cambiada en un solo lugar, nombrada; variable declarada con uno de los seis tipos leídos según su uso
←asigna;DIVdivisión de números enteros,MODresto; precedenciaNOT→* / DIV MOD→+ -→ comparaciones →AND→OR- usa las rutinas de biblioteca de la inserta con sus nombres exactos 9618:
LENGTH,MID,TO_UPPER,NUM_TO_STR,INT,RAND