Data types and records · Tipos de datos y registros
| English | Español |
|---|---|
| data type/ˈdeɪtə taɪp/ | tipo de dato |
| field/fiːld/ | campo |
| record/ˈrekɔːd/ | registro |
| record structure/ˈrekɔːd ˈstrʌktʃə/ | estructura de registro |
| dot notation/dɒt nəʊˈteɪʃn/ | notación puntera |
The most expensive data-type decision in history
- In the 1960s memory cost more than programmers. To save two characters per date, years were stored as two digits:
99meant 1999. - Nobody expected the code to outlive the century. It did, and on 1 January 2000 every one of those fields would read as 1900. Governments and companies spent an estimated $300 billion checking and fixing it.
- The bug was not a typo. It was a data type 数据类型 chosen for the memory of 1965 and kept for the dates of 2000.
- This lesson is how to pick the type that fits the data, and how to bundle values that belong together into a record 记录.
La decisión de tipo de dato más costosa en la historia
- En la década de 1960, la memoria era más cara que los programadores. Para ahorrar dos caracteres por fecha, los años se almacenaban con dos dígitos:
99significaba 1999. - Nadie esperaba que el código sobreviviera al siglo. Lo hizo, y el 1 de enero de 2000 cada uno de esos campos mostraría 1900. Gobiernos y empresas gastaron una estimación de 300 mil millones de dólares revisando y corrigiéndolo.
- El error no fue un error tipográfico. Fue un tipo de dato 数据类型 elegido para la memoria de 1965 y mantenido para las fechas de 2000.
- Esta lección explica cómo elegir el tipo adecuado para los datos y cómo agrupar valores que pertenecen juntos en un registro 记录.
The six basic types
| Type | Holds | Use it for |
|---|---|---|
INTEGER |
a whole number, 42, -7 |
counts, indexes, IDs |
REAL |
a number with a fractional part, 3.14 |
measurements, averages |
CHAR |
a single character, 'A' |
a grade letter, a menu choice |
STRING |
characters in quotes, "Hello" |
text |
BOOLEAN |
TRUE or FALSE |
flags |
DATE |
a calendar date | dates of birth, deadlines |
Pseudocode also names two structured types: ARRAY and FILE
Los seis tipos básicos
| Tipo | Almacena | Úsalo para |
|---|---|---|
INTEGER |
un número entero, 42, -7 |
conteos, índices, IDs |
REAL |
un número con parte fraccionaria, 3.14 |
mediciones, promedios |
CHAR |
un solo carácter, 'A' |
una letra de calificación, una opción de menú |
STRING |
caracteres entre comillas, "Hello" |
texto |
BOOLEAN |
TRUE o FALSE |
banderas |
DATE |
una fecha del calendario | fechas de nacimiento, plazos |

El pseudocódigo también nombra dos tipos estructurados: ARRAY (matriz) y FILE (archivo)
Which data type best stores a yes/no flag like "in stock"? · ¿Qué tipo de dato almacena mejor una bandera de sí/no como "en stock"?
A flag has two states, so BOOLEAN (TRUE/FALSE) is the precise choice — not the strings "yes"/"no". · Una bandera tiene dos estados, por lo que BOOLEANO (VERDADERO/FALSO) es la elección precisa — no las cadenas "sí"/"no".
A real (floating-point) type should be used to store a measurement such as a temperature. · Un tipo real (de coma flotante) debe usarse para almacenar una medición como una temperatura.
Whole counts use integers; measurements use reals. · Los conteos enteros usan enteros; las mediciones usan reales.
Choose by how the value is used
- A type is decided by what the program will do with the value, not by how it looks.
- The number of students is
INTEGER; the class's average mark isREAL, because it has a fractional part; whether a student has paid isBOOLEAN. - An array index is always
INTEGER. A single grade letter isCHAR; an email address isSTRING. - A phone number is a
STRING: it starts with0, and nobody ever adds two phone numbers.
Elige según cómo se usa el valor
- Un tipo se decide por lo que el programa hará con el valor, no por cómo se ve.
- El número de estudiantes es
INTEGER; la nota media de la clase esREAL, porque tiene una parte fraccionaria; si un estudiante ha pagado esBOOLEAN. - Un índice de matriz es siempre
INTEGER. Una sola letra de calificación esCHAR; una dirección de correo electrónico esSTRING. - Un número de teléfono es un
STRING: empieza con0, y nadie suma nunca dos números de teléfono.
Match each value to the best data type for it. · Asocia cada valor con el mejor tipo de dato para él.
Pick the precise type: BOOLEAN for a flag, REAL for fractional values, INTEGER for whole counts, STRING for text. · Elige el tipo preciso: BOOLEANO para una bandera, REAL para valores fraccionarios, ENTERO para conteos enteros, CADENA para texto.
Which data type should store a phone number such as 07700 900123? · ¿Qué tipo de dato debería almacenar un número de teléfono como 07700 900123?
An INTEGER would drop the leading zero, and no program adds or multiplies phone numbers. The digits are text. · Un ENTERO eliminaría el cero inicial, y ningún programa suma o multiplica números de teléfono. Los dígitos son texto.
Worked example: give the appropriate data type
| Data | Type | Because |
|---|---|---|
| number of items in stock | INTEGER |
a whole count |
| price of an item | REAL |
has pence, a fractional part |
| whether the item is on offer | BOOLEAN |
only two states |
the item's category code, 'F' |
CHAR |
exactly one character |
| the supplier's name | STRING |
text |
| the date the item was delivered | DATE |
a calendar date |
- Give the pseudocode name, not the language you happen to know:
BOOLEAN, notbool;REAL, notfloat.
Ejemplo resuelto: asigna el tipo de dato apropiado
| Dato | Tipo | Porque |
|---|---|---|
| número de artículos en stock | INTEGER |
un conteo entero |
| precio de un artículo | REAL |
tiene peniques, una parte fraccionaria |
| si el artículo está en oferta | BOOLEAN |
solo dos estados |
el código de categoría del artículo, 'F' |
CHAR |
exactamente un carácter |
| el nombre del proveedor | STRING |
texto |
| la fecha de entrega del artículo | DATE |
una fecha del calendario |
- Escribe el nombre del pseudocódigo, no el lenguaje que conozcas:
BOOLEAN, nobool;REAL, nofloat.
The data type of an array index is always ____. · El tipo de dato de un índice de matriz es siempre ____.
An index counts positions, so it is a whole number. Names[2.5] has no meaning. · Un índice cuenta posiciones, por lo que es un número entero. Names[2.5] no tiene sentido.
Records
- A record (a record structure 记录结构) holds a set of data items of different data types under one identifier. Each item is a field 字段.
- Use one when several values always describe one thing: a stock item, a customer, a student.
One identifier, four fields, four types
Registros
- Un registro (una estructura de registro 记录结构) almacena un conjunto de elementos de datos de diferentes tipos bajo un único identificador. Cada elemento es un campo 字段.
- Usa uno cuando varios valores describen siempre una misma cosa: un artículo de inventario, un cliente, un estudiante.
TYPE TStockItem
DECLARE ItemID : INTEGER
DECLARE Category : STRING
DECLARE ItemCost : REAL
DECLARE InStock : BOOLEAN
ENDTYPE

Un identificador, cuatro campos, cuatro tipos
A record is used to: · Un registro se usa para:
A record bundles fields of (possibly) different types that describe one thing. An array holds many values of the same type. · Un registro agrupa campos de (posiblemente) diferentes tipos que describen una cosa. Una matriz contiene muchos valores del mismo tipo.
Declaring and using a record
TYPE … ENDTYPEdefines the type. Then declare variables of it, singly or as an array:
- Reach a field with dot notation 点号表示法, to write and to read:
Declarar y usar un registro
TYPE … ENDTYPEdefine el tipo. Luego declara variables de ese tipo, individualmente o como una matriz:
DECLARE Item1 : TStockItem
DECLARE Items : ARRAY[1:100] OF TStockItem
- Accede a un campo usando notación punteada 点号表示法, tanto para escribir como para leer:
Item1.Category ← "Fruit"
OUTPUT Item1.Category, " costs ", Item1.ItemCost
Items[7].InStock ← FALSE
A record groups fields under one name · Un registro agrupa campos bajo un solo nombre
A record bundles related fields together. Each field is a named label you reach with dot notation — Item1.Category — not by a numeric index. · Un registro agrupa campos relacionados. Cada campo es una etiqueta con nombre a la que accedes mediante notación por puntos — Item1.Category — no mediante un índice numérico.
To set the Category field of a record variable Item1, you write: · Para establecer el campo Category de una variable de registro Item1, escribes:
Dot notation record.field reaches a field of a record. · La notación de puntos record.field accede a un campo de un registro.
Worked example: the club membership file
- A club stores, for each student, a student ID (a string), a name, a date of birth and up to three club numbers. Declare the record type, an array for 3000 students, and store a name in the first element.
- The marks:
TYPEwith the identifier andENDTYPE; every field declared with a suitable type; the array with its bounds andOF Student; the field reached with the index and the dot.
Ejemplo resuelto: el archivo de membresía del club
- Un club almacena, para cada estudiante, un ID de estudiante (cadena), un nombre, una fecha de nacimiento y hasta tres números de club. Declara el tipo de registro, una matriz para 3000 estudiantes y almacena un nombre en el primer elemento.
TYPE Student
DECLARE StudentID : STRING
DECLARE Name : STRING
DECLARE DateOfBirth : DATE
DECLARE Club : ARRAY[1:3] OF INTEGER
ENDTYPE
DECLARE Membership : ARRAY[1:3000] OF Student
Membership[1].Name ← "Li Wei"
- Las notas:
TYPEcon el identificador yENDTYPE; cada campo declarado con un tipo adecuado; la matriz con sus límites yOF Student; el campo alcanzado con el índice y el punto.
Put the lines of the club membership declaration in order. · Ordena las líneas de la declaración de membresía del club.
Define the type, close it, declare a variable or array of it, then use index and dot to reach a field. · Define el tipo, ciérralo, declara una variable o matriz de ese tipo, luego usa índice y punto para acceder a un campo.
Worked example: state the error in the declaration
- Three errors, each a mark: the type has no
ENDTYPE; the fieldPricehas no data type; andTotalwill holdSeats * Price, an arithmetic result, so it cannot be aSTRING. - The examiner's usual three: a missing
ENDTYPE, a field without a type, a field of the wrong type for what is done with it.
Ejemplo resuelto: señala el error en la declaración
TYPE TBooking
DECLARE Seats : INTEGER
DECLARE Price
DECLARE Total : STRING
- Tres errores, cada uno vale una marca: el tipo no tiene
ENDTYPE; el campoPriceno tiene tipo de dato; yTotalcontendráSeats * Price, un resultado aritmético, por lo que no puede ser unSTRING. - Los tres errores habituales del examinador: falta de
ENDTYPE, un campo sin tipo, un campo con tipo incorrecto para su uso.
Which of these are errors in a record declaration? Select all · todos that apply. · ¿Cuáles de estos son errores en una declaración de registro? Selecciona todos los que correspondan.
Different types in one record is the whole point of a record. The other three are the errors examiners plant. · Tener diferentes tipos en un registro es todo el punto de un registro. Las otras tres son los errores que colocan los examinadores.
Record, array, or plain variables
- Values that always belong together and have different types: a record.
- Many values of the same type under one name: an array (next lesson).
- A table of rows where each row has mixed fields: an array of records,
Members[i].Name. - Unrelated values: separate variables. Bundling them gains nothing.
Registro, matriz o variables simples
- Valores que siempre pertenecen juntos y tienen tipos diferentes: un registro.
- Muchos valores del mismo tipo bajo un mismo nombre: una matriz (siguiente lección).
- Una tabla de filas donde cada fila tiene campos mixtos: una matriz de registros,
Members[i].Name. - Valores no relacionados: variables separadas. Agruparlos no aporta nada.
An array of records lets one identifier hold a table in which every row has fields of different types. · Una matriz de registros permite que un solo identificador contenga una tabla en la que cada fila tiene campos de diferentes tipos.
Members[i] is one row (a record); Members[i].Name is one cell. The array gives the rows, the record gives the mixed columns. · Members[i] es una fila (un registro); Members[i].Name es una celda. La matriz proporciona las filas, el registro proporciona las columnas mixtas.
Marks that slip away
- A yes/no value is a
BOOLEAN, not the strings"yes"and"no". - A phone number or an ID that starts with
0is aSTRING, never anINTEGER. - Money in a
REALpicks up rounding errors; many systems store whole pennies as anINTEGER. - Every field is a
DECLAREline with a type, and the type ends withENDTYPE. The index goes on the array, the dot on the field:Members[3].Name.
Marcas que se pierden fácilmente
- Un valor de sí/no es un
BOOLEAN, no las cadenas"yes"y"no". - Un número de teléfono o un ID que empieza con
0es unSTRING, nunca unINTEGER. - El dinero en un
REALacumula errores de redondeo; muchos sistemas almacenan peniques enteros como unINTEGER. - Cada campo es una línea
DECLAREcon un tipo, y el tipo termina conENDTYPE. El índice va en la matriz, el punto en el campo:Members[3].Name.
You've got it
- six basic types,
INTEGER,REAL,CHAR,STRING,BOOLEAN,DATE, chosen by what the program does with the value - a record holds fields of different types under one identifier:
TYPE … DECLARE field : type … ENDTYPE - declare variables or arrays of the type, and reach a field with dot notation:
Membership[1].Name ← "Li Wei" - the errors the examiner plants: no
ENDTYPE, a field with no type, a field typed wrongly for its use
Ya lo tienes
- seis tipos básicos,
INTEGER,REAL,CHAR,STRING,BOOLEAN,DATE, elegidos por lo que el programa hace con el valor - un registro contiene campos de tipos diferentes bajo un único identificador:
TYPE … DECLARE field : type … ENDTYPE - declara variables o matrices del tipo, y accede a un campo con notación punteada:
Membership[1].Name ← "Li Wei" - los errores que coloca el examinador: falta de
ENDTYPE, un campo sin tipo, un campo con tipo incorrecto para su uso