Data types and records · Tipos de dados e registros
| English | Português |
|---|---|
| data type/ˈdeɪtə taɪp/ | tipo de dado |
| field/fiːld/ | campo |
| record/ˈrekɔːd/ | registrar |
| record structure/ˈrekɔːd ˈstrʌktʃə/ | estrutura de registro |
| dot notation/dɒt nəʊˈteɪʃn/ | notação pontual |
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 记录.
A decisão de tipo de dado mais cara da história
- Na década de 1960, memória custava mais que programadores. Para economizar dois caracteres por data, anos eram armazenados com dois dígitos:
99significava 1999. - Ninguém esperava que o código sobrevivesse ao século. Ele sobreviveu, e em 1º de janeiro de 2000 cada um desses campos leria como 1900. Governos e empresas gastaram estimados US$ 300 bilhões verificando e consertando isso.
- O bug não foi um erro de digitação. Foi um tipo de dado 数据类型 escolhido para a memória de 1965 e mantido para as datas de 2000.
- Esta aula ensina como escolher o tipo que se adequa aos dados, e como agrupar valores que pertencem juntos num registo 记录.
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
Os seis tipos básicos
| Tipo | Contém | Use-o para |
|---|---|---|
INTEGER |
um número inteiro, 42, -7 |
contagens, índices, IDs |
REAL |
um número com parte fracionária, 3.14 |
medições, médias |
CHAR |
um único caractere, 'A' |
uma letra de nota, uma escolha de menu |
STRING |
caracteres entre aspas, "Hello" |
texto |
BOOLEAN |
TRUE ou FALSE |
flags (indicadores) |
DATE |
uma data do calendário | datas de nascimento, prazos |

A pseudocódigo também nomeia dois tipos estruturados: ARRAY e FILE
Which data type best stores a yes/no flag like "in stock"? · Qual tipo de dado melhor armazena uma bandeira sim/não como "em estoque"?
A flag has two states, so BOOLEAN (TRUE/FALSE) is the precise choice — not the strings "yes"/"no". · Uma bandeira tem dois estados, então BOOLEAN (VERDADEIRO/FALSO) é a escolha precisa — não as strings "sim"/"não".
A real (floating-point) type should be used to store a measurement such as a temperature. · Um tipo real (ponto flutuante) deve ser usado para armazenar uma medida como temperatura.
Whole counts use integers; measurements use reals. · Contagens inteiras usam inteiros; medições usam reais.
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.
Escolha pelo uso do valor
- Um tipo é definido pelo que o programa fará com o valor, não pela sua aparência.
- O número de alunos é
INTEGER; a média da turma éREAL, pois tem uma parte fracionária; se um aluno pagou éBOOLEAN. - Um índice de array é sempre
INTEGER. Uma única letra de nota éCHAR; um endereço de email éSTRING. - Um número de telefone é um
STRING: começa com0, e ninguém jamais soma dois números de telefone.
Match each value to the best data type for it. · Combine cada valor com o melhor tipo de dado para ele.
Pick the precise type: BOOLEAN for a flag, REAL for fractional values, INTEGER for whole counts, STRING for text. · Escolha o tipo preciso: BOOLEAN para uma bandeira, REAL para valores fracionários, INTEGER para contagens inteiras, STRING para texto.
Which data type should store a phone number such as 07700 900123? · Que tipo de dado deve armazenar um número de telefone como 07700 900123?
An INTEGER would drop the leading zero, and no program adds or multiplies phone numbers. The digits are text. · Um INTEGER perderia o zero inicial, e nenhum programa soma ou multiplica números de telefone. Os dígitos são 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.
Exemplo resolvido: dê o tipo de dado adequado
| Dado | Tipo | Porquê |
|---|---|---|
| número de itens em stock | INTEGER |
uma contagem inteira |
| preço de um item | REAL |
tem pence, uma parte fracionária |
| se o item está em promoção | BOOLEAN |
apenas dois estados |
código de categoria do item, 'F' |
CHAR |
exatamente um caractere |
| nome do fornecedor | STRING |
texto |
| data de entrega do item | DATE |
uma data do calendário |
- Dê o nome do pseudocódigo, não a linguagem que você conhece:
BOOLEAN, nãobool;REAL, nãofloat.
The data type of an array index is always ____. · O tipo de dado de um índice de array é sempre ____.
An index counts positions, so it is a whole number. Names[2.5] has no meaning. · Um índice conta posições, portanto é um número inteiro. Names[2.5] não tem significado.
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
Registos
- Um registo (uma estrutura de registo 记录结构) armazena um conjunto de itens de dados de diferentes tipos sob um único identificador. Cada item é um campo 字段.
- Use um quando vários valores descrevem sempre uma coisa: um item em stock, um cliente, um aluno.
TYPE TStockItem
DECLARE ItemID : INTEGER
DECLARE Category : STRING
DECLARE ItemCost : REAL
DECLARE InStock : BOOLEAN
ENDTYPE

Um identificador, quatro campos, quatro tipos
A record is used to: · Um registro é usado para:
A record bundles fields of (possibly) different types that describe one thing. An array holds many values of the same type. · Um registro agrupa campos de (possivelmente) tipos diferentes que descrevem uma coisa. Uma matriz armazena muitos valores do mesmo 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:
Declaração e uso de um registo
TYPE … ENDTYPEdefine o tipo. Depois declare variáveis desse tipo, individualmente ou como um array:
DECLARE Item1 : TStockItem
DECLARE Items : ARRAY[1:100] OF TStockItem
- Acesse um campo com notação de ponto 点号表示法, para escrever e ler:
Item1.Category ← "Fruit"
OUTPUT Item1.Category, " costs ", Item1.ItemCost
Items[7].InStock ← FALSE
A record groups fields under one name · Um registro agrupa campos sob um único nome
A record bundles related fields together. Each field is a named label you reach with dot notation — Item1.Category — not by a numeric index. · Um registro agrupa campos relacionados juntos. Cada campo é um rótulo nomeado que você acessa com notação de ponto — Item1.Categoria — não por índice numérico.
To set the Category field of a record variable Item1, you write: · Para definir o campo Category da variável de registro Item1, você escreve:
Dot notation record.field reaches a field of a record. · A notação ponto record.field acessa um campo de um 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.
Exemplo resolvido: o ficheiro de membros do clube
- Um clube armazena, para cada aluno, um ID de aluno (uma string), um nome, uma data de nascimento e até três números de clube. Declare o tipo de registo, um array para 3000 alunos e armazene um nome no primeiro 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"
- As notas:
TYPEcom o identificador eENDTYPE; cada campo declarado com um tipo adequado; o array com os seus limites eOF Student; o campo acessado com o índice e o ponto.
Put the lines of the club membership declaration in order. · Coloque as linhas da declaração de filiação ao clube em ordem.
Define the type, close it, declare a variable or array of it, then use index and dot to reach a field. · Defina o tipo, feche-o, declare uma variável ou matriz dele, depois use índice e ponto para acessar um 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.
Exemplo resolvido: indique o erro na declaração
TYPE TBooking
DECLARE Seats : INTEGER
DECLARE Price
DECLARE Total : STRING
- Três erros, cada um vale uma marca: o tipo não tem
ENDTYPE; o campoPricenão tem tipo de dado; eTotalconteráSeats * Price, um resultado aritmético, então não pode ser umSTRING. - Os três erros habituais do examinador: um
ENDTYPEausente, um campo sem tipo, um campo do tipo errado para o que é feito com ele.
Which of these are errors in a record declaration? Select all · todos that apply. · Quais destes são erros em uma declaração de registro? Selecione todos que se aplicam.
Different types in one record is the whole point of a record. The other three are the errors examiners plant. · Diferentes tipos em um registro são o ponto principal de um registro. As outras três são os erros que os examinadores colocam.
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.
Registo, array ou variáveis simples
- Valores que sempre pertencem juntos e têm tipos diferentes: um registo.
- Muitos valores do mesmo tipo sob um único nome: um array (próxima aula).
- Uma tabela de linhas onde cada linha tem campos mistos: um array de registros,
Members[i].Name. - Valores não relacionados: variáveis separadas. Agrupá-los não traz vantagens.
An array of records lets one identifier hold a table in which every row has fields of different types. · Uma matriz de registros permite que um único identificador segure uma tabela em que cada linha tem campos de tipos diferentes.
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] é uma linha (um registro); Members[i].Name é uma única célula. A matriz fornece as linhas, o registro fornece as colunas mistas.
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 escapam
- Um valor sim/não é um
BOOLEAN, não as strings"yes"e"no". - Um número de telefone ou um ID que começa com
0é umSTRING, nunca umINTEGER. - Dinheiro em um
REALacumula erros de arredondamento; muitos sistemas armazenam centavos inteiros como umINTEGER. - Cada campo é uma linha de
DECLAREcom um tipo, e o tipo termina comENDTYPE. O índice vai no array, o ponto no 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
Entendeu?
- seis tipos básicos,
INTEGER,REAL,CHAR,STRING,BOOLEAN,DATE, escolhidos pelo que o programa faz com o valor - um registro contém campos de tipos diferentes sob um único identificador:
TYPE … DECLARE field : type … ENDTYPE - declare variáveis ou arrays do tipo, e acesse um campo com notação de ponto:
Membership[1].Name ← "Li Wei" - os erros que o examinador planta: sem
ENDTYPE, um campo sem tipo, um campo digitado erroneamente para seu uso