CIE AS & A Level Computer Science, section 10.1 (Data types and records)
What a record is
A record is a data structure that holds a set of related data items (fields) of different data types under one identifier. It lets you treat all the data about one thing (a student, a book) as a single item.
Defining a record in pseudocode
TYPE TStudent
DECLARE Name : STRING
DECLARE Age : INTEGER
DECLARE Mark : REAL
ENDTYPE
DECLARE Student1 : TStudent
Writing to and reading from a record
Use the dot notation Identifier.Field.
Student1.Name ← "Aisha"
Student1.Age ← 16
Student1.Mark ← 78.5
OUTPUT Student1.Name, " scored ", Student1.Mark
An array of records
DECLARE Class : ARRAY[1:30] OF TStudent
Class[1].Name ← "Ben"
Python
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
mark: float
s1 = Student("Aisha", 16, 78.5)
print(s1.name, s1.mark) # Aisha 78.5
Records and arrays compared
| Record | Array |
|---|---|
| fields can have different data types | all elements have the same data type |
| fields accessed by name | elements accessed by index |
Benefits
Related data is kept together, so the program is easier to read, and a whole record can be passed to a procedure or written to a file in one operation.
Common mistake: saying all the fields in a record must have the same type. That is true for an array; a record holds different types. Also, declare the type first, then declare a variable of that type.
Exam tip: write the TYPE ... ENDTYPE definition with a DECLARE for each field, then use Identifier.Field to read or write. Use meaningful field names.
Check yourself
What is a record?
A data structure holding a set of related fields, of different data types, under one identifier.
Write the statement to set the field Age of the record Student1 to 17.
Student1.Age ← 17.
What is one difference between a record and an array?
A record can hold fields of different data types, while all the elements of an array have the same type.