📑 Contents

Chapter 13.1: User-Defined Data Types

9618 Computer Science - Data Representation

📚 Learning Objectives
📋 Prior Knowledge Required
🌟 Did You Know?

User-defined data types allow programmers to create custom data structures that exactly match a program's requirements. They are built using primitive data types provided by a programming language, or other data types that have been previously defined. This makes programs much easier to code, read, and debug!

User-Defined Data Types Non-Composite • Enumerated • Pointer Composite • Record • Set • Class/Object

1. Introduction to User-Defined Data Types

User-defined data types are custom data structures created by programmers to match the specific needs of a program. They are built using primitive data types (such as INTEGER, REAL, STRING, BOOLEAN) or other data types that have been previously defined in a program.

📖 Definition

A user-defined data type is a data type based on an existing data type or other data types that have been defined by a programmer. User-defined data types can make programs much easier to code, read, and debug.

1.1 Why Use User-Defined Data Types?

📝 Reasons for Using User-Defined Types

1.2 Categories of User-Defined Data Types

Category Description Examples
Non-Composite Made up of a single data item; defined without referencing another data type Enumerated types, Pointer types
Composite Made up of multiple data items, often of different types; references other data types in its definition Records, Sets, Classes/Objects
💡 Exam Tip

Remember: Non-Composite = Single data type (no references to other types), while Composite = Multiple data types (contains references to other types in its definition). A record is composite because it references other types like STRING and INTEGER!

2. Non-Composite Data Types: Enumerated

Enumerated data type is a non-composite user-defined data type that defines a list of all possible values with an implied order. If you are using lots of constants in your program that are all related to each other, it is a good idea to keep them together using an enumerated type.

📖 Key Characteristics of Enumerated Types

2.1 Enumerated Type Definition Syntax

Pseudocode Syntax:

TYPE  = (value1, value2, value3, ...)
📝 Example: Days of the Week
TYPE TDays = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)

DECLARE Today : TDays
DECLARE Yesterday : TDays
DECLARE Tomorrow : TDays

Today ← Wednesday
Yesterday ← Today - 1      // Sets to Tuesday
Tomorrow ← Today + 1       // Sets to Thursday
📝 Example: Months of the Year
TYPE TMonth = (January, February, March, April, May, June, 
              July, August, September, October, November, December)

DECLARE thisMonth : TMonth
DECLARE nextMonth : TMonth

thisMonth ← January
nextMonth ← thisMonth + 1   // nextMonth is now February
Enumerated Type: TDays Monday Tuesday Wednesday Thursday Friday Saturday Sunday [0] [1] [2] ← Today [3] [4] [5] [6] Values are ordinal (ordered) - can use +1, -1 operations
💡 Exam Tip

Type names usually begin with T to aid the programmer (e.g., TDays, TMonth). Remember: enumerated values are NOT strings - they don't use quotation marks! The implied order means you can use arithmetic like Today + 1 to get the next value.

3. Non-Composite Data Types: Pointer

Pointer data type is a non-composite user-defined data type that stores the memory address of where data is stored, rather than the data itself. Pointers are used to reference a memory location and are essential for dynamic data structures like linked lists.

📖 Key Characteristics of Pointer Types

3.1 Pointer Type Definition Syntax

Pseudocode Syntax:

TYPE  = ^    // ^ indicates pointer to TypeName
📝 Example: Integer Pointer
// Define pointer type
TYPE TIntegerPointer = ^INTEGER

// Declare pointer variable
DECLARE MyIntegerPointer : TIntegerPointer

// Declare ordinary variables
DECLARE Number1, Number2 : INTEGER
Number1 ← 100

// Store address of Number1 in pointer
MyIntegerPointer ← @Number1    // @ gets the address

// Dereference: get value at the address
Number2 ← MyIntegerPointer^ * 2   // Number2 becomes 200
📝 Example: Pointer to User-Defined Type
TYPE TMonth = (January, February, March, ...)
TYPE TMonthPointer = ^TMonth    // Pointer to TMonth

DECLARE monthPointer : TMonthPointer
DECLARE thisMonth : TMonth
DECLARE myMonth : TMonth

thisMonth ← March
monthPointer ← @thisMonth       // Pointer now holds address

// Dereferencing - get value at address
myMonth ← monthPointer^         // myMonth becomes March
Pointer Memory Model Number1 100 Number2 200 MyIntegerPointer @Number1 Address: 0x1000 Address: 0x1004 @Number1 → gets address (0x1000) MyIntegerPointer^ → dereferences to value (100)
⚠️ Important: Key Symbols

4. Composite Data Types: Record

Record data type is a composite user-defined data type that contains a fixed number of components (fields), which can be of different data types. Records allow the programmer to collect together related values with different data types into a single structure.

📖 Key Characteristics of Records

4.1 Record Type Definition Syntax

Pseudocode Syntax:

TYPE 
    DECLARE  : 
    DECLARE  : 
    ...
ENDTYPE
📝 Example: Employee Record
TYPE EmployeeRecord
    DECLARE EmployeeFirstName : STRING
    DECLARE EmployeeFamilyName : STRING
    DECLARE DateEmployed : DATE
    DECLARE Salary : CURRENCY
ENDTYPE

DECLARE Employee1 : EmployeeRecord

// Assign values using dot notation
Employee1.EmployeeFirstName ← "John"
Employee1.EmployeeFamilyName ← "Smith"
Employee1.DateEmployed ← #16/05/2017#
Employee1.Salary ← 45000.00

// Output a field
OUTPUT Employee1.EmployeeFirstName
📝 Example: Student Record with Array
TYPE StudentType
    DECLARE Name : STRING
    DECLARE DateOfBirth : DATE
    DECLARE Height : REAL
    DECLARE NumberOfSiblings : INTEGER
    DECLARE IsFullTimeStudent : BOOLEAN
ENDTYPE

// Declare single record
DECLARE Person : StudentType
Person.Name ← "Fred"
Person.NumberOfSiblings ← 3
Person.IsFullTimeStudent ← TRUE

// Declare array of records
DECLARE Students : ARRAY[1:100] OF StudentType
Students[1].Name ← "Fred"
OUTPUT Students[1].Name
Record Structure: StudentType StudentType Name : STRING DateOfBirth : DATE Height : REAL IsFullTimeStudent : BOOLEAN Access: Person.Name, Person.Height
💡 Exam Tip

Records are the most useful and widely used composite data type! They allow you to represent real-world entities like students, products, or customers. Remember to use dot notation to access individual fields: RecordName.FieldName

5. Composite Data Types: Set

Set data type is a composite user-defined data type that represents an unordered collection of unique elements. Sets are useful for situations where duplication is not allowed and where membership testing is common.

📖 Key Characteristics of Sets

5.1 Set Type Definition Syntax

Pseudocode Syntax:

TYPE  = SET OF 
DEFINE  (value1, value2, value3, ...) : 
📝 Example: Set of Vowels
TYPE SLetter = SET OF CHAR
DEFINE vowels ('a', 'e', 'i', 'o', 'u') : SLetter

// Membership testing
IF 'e' ISIN vowels THEN
    OUTPUT "'e' is a vowel"
ENDIF
📝 Example: Set of Colours
TYPE ColourSet = SET OF STRING
DEFINE Colours ("Red", "Green", "Blue") : ColourSet

IF "Green" ISIN Colours THEN
    OUTPUT "Green is in the set"
ENDIF

5.2 Set Operations

Operation Symbol Description
Union ∪ or | All elements from both sets
Intersection ∩ or & Elements common to both sets
Difference − or − Elements in first set but not in second
Symmetric Difference △ or ^ Elements in either set but not in both
Membership ISIN Check if element exists in set
Set Operations Visualization A ∪ B Union A ∩ B Intersection A-B Difference A △ B Symmetric Diff All elements are unique - no duplicates allowed!
🧠 Memory Trick

Think of sets like a club membership list: Each person can only be on the list once (unique), the order doesn't matter (unordered), and you can check if someone is a member (ISIN), add new members, or remove members!

6. Composite Data Types: Classes and Objects

Class is a composite data type that includes variables of given data types (attributes/properties) and methods (code routines that can be run by an object in that class). An object is defined from a given class - several objects can be defined from the same class.

📖 Key Characteristics of Classes

6.1 Classes vs Records

Feature Record Class
Contains Only data fields Data fields AND methods
Purpose Group related data Define objects with behavior
Usage Direct variable declaration Object instantiation
Example Student record with Name, Age Car class with color, model, drive()
📝 Example: Car Class Concept

A Car class might include:

Objects created from this class: myCar, yourCar, companyCar - each has its own color, model, etc.

Class as Blueprint → Objects as Instances CLASS: Car + color: STRING + model: STRING + speed: INTEGER + drive() creates myCar color="Red" model="Sedan" speed=0 yourCar color="Blue" model="SUV" speed=60 companyCar color="Black" model="Van" speed=45 Each object has its own copy of attributes!
🌟 Did You Know?

Classes and objects are fundamental to Object-Oriented Programming (OOP). They will be covered in more depth in Chapter 20 (Further Programming). For now, remember that a class is a user-defined data type that combines data AND methods!

7. Comparison of User-Defined Data Types

Data Type Category Description Use Case
Enumerated Non-Composite List of named, fixed values with implied order Days of week, months, directions
Pointer Non-Composite Stores memory address of data Dynamic structures, linked lists
Record Composite Groups related fields of different types Student data, employee records
Set Composite Unordered collection of unique elements Vowels, colours, user IDs
Class Composite Blueprint with data AND methods Objects with behavior

7.1 Choosing the Right Data Type

📝 Decision Guide
Choosing User-Defined Data Type References other types? NO YES Non-Composite • Enumerated • Pointer (Single data type) Composite • Record • Set • Class/Object
❌ Common Mistakes to Avoid

8. Exam-Style Questions

1. A programmer may choose to use a user-defined data type when writing a program. Give an example of a non-composite user-defined data type and explain why its use by a programmer is different to use of an in-built data type. [3 marks]

Answer:

  • Example: Enumerated or Pointer
  • A built-in data type has a pre-defined range of possible values
  • Built-in types are used by any program universally
  • User-defined types: the programmer defines a specific range unique to that program
  • User-defined types are tailored to the specific requirements of the program

Additional points for deeper understanding: User-defined types improve code readability and make programs easier to debug by restricting values to meaningful options.

2. A program is to be written to handle data relating to animals kept in a zoo. The programmer chooses to use a record user-defined data type. Explain what a record user-defined data type is. [2 marks]

Answer:

  • A record is a composite data type
  • It contains a fixed number of components/fields
  • Components can be of different data types
  • It groups related data together in one structure
  • Each field has a name and specific data type
3. Explain the advantage of using a record user-defined data type. [2 marks]

Answer:

  • Related data can be referenced with one construct
  • Very flexible because different types allowed for the components
  • A value for a component can be accessed individually using dot notation
  • Makes code easier to read and maintain
  • Can create arrays of records for multiple items
4. Write pseudocode for the definition of a record type which is to be used to store: animal name, animal age, number in zoo, and location in the zoo. [4 marks]

Answer:

TYPE Animal
    DECLARE AnimalName : STRING
    DECLARE AnimalAge : INTEGER
    DECLARE NumberInZoo : INTEGER
    DECLARE LocationInZoo : STRING
ENDTYPE

Additional notes: Type name should start with T convention (e.g., TAnimal), and field names should be descriptive. Each field must have an appropriate data type.

5. Define an enumerated data type for the four cardinal directions (North, East, South, West). Then declare a variable and assign it a value. [3 marks]

Answer:

TYPE TDirection = (North, East, South, West)

DECLARE CurrentDirection : TDirection
CurrentDirection ← North

// Can also use ordinal operations
CurrentDirection ← CurrentDirection + 1  // Now East

Additional points: Values are ordinal, so you can use +1, -1 operations. Values are NOT strings and do not use quotation marks.

8. Exam-Style Questions (Continued)

6. Explain what is meant by a pointer data type and how dereferencing works. Use an example in your answer. [4 marks]

Answer:

  • A pointer is a non-composite data type that stores a memory address
  • It references a memory location where data is stored
  • Dereferencing means accessing the value at the memory address
  • Use ^ symbol to dereference (e.g., MyPointer^)
TYPE TIntPointer = ^INTEGER
DECLARE ptr : TIntPointer
DECLARE num : INTEGER
num ← 100
ptr ← @num        // ptr now holds address of num
OUTPUT ptr^       // Dereference: outputs 100
7. Explain the difference between a non-composite and a composite user-defined data type. Give an example of each. [4 marks]

Answer:

  • Non-composite: Defined without referencing another data type; contains only one data item
  • Examples: Enumerated types, Pointer types
  • Composite: References other data types in its definition; contains multiple data items
  • Examples: Records, Sets, Classes

Key distinction: A record is composite because it references STRING, INTEGER, etc. in its definition. An enumerated type is non-composite because it only defines a list of values, not referencing any other type.

8. Describe the key features of a set data type. Give an example of when a set would be appropriate to use. [4 marks]

Answer:

  • Sets contain unordered elements
  • No duplicate values are allowed
  • Supports mathematical operations: union, intersection, difference
  • Can test for membership (ISIN)
  • Example use: Storing vowels, colours, user IDs where uniqueness is required
TYPE SVowel = SET OF CHAR
DEFINE vowels ('a', 'e', 'i', 'o', 'u') : SVowel
IF 'e' ISIN vowels THEN
    OUTPUT "It's a vowel"
ENDIF
9. Write pseudocode to define a Student record type with fields for Name (STRING), Age (INTEGER), and Grade (STRING). Then declare an array of 50 students and assign values to the first student. [5 marks]

Answer:

TYPE TStudent
    DECLARE Name : STRING
    DECLARE Age : INTEGER
    DECLARE Grade : STRING
ENDTYPE

DECLARE Students : ARRAY[1:50] OF TStudent

// Assign values to first student
Students[1].Name ← "Alice"
Students[1].Age ← 17
Students[1].Grade ← "A"

// Output first student's name
OUTPUT Students[1].Name

Key points: Use dot notation with array index to access fields. The record type groups related data together efficiently.

10. Explain why user-defined data types are necessary in programming. Give two specific reasons with examples. [4 marks]

Answer:

  • No suitable built-in type exists: When data requires a unique structure (e.g., a 'Student' type with multiple attributes)
  • Specific behaviors needed: For operations not available in standard types (e.g., restricting input to predefined values using enumerated types)
  • Real-world modeling: To represent real-world entities accurately (e.g., Employee record with name, salary, department)
  • Code organization: Makes programs easier to code, read, and debug
  • Reusability: Once defined, the type can be used throughout the program
11. Compare and contrast a class and a record. What additional feature does a class have that a record does not? [3 marks]

Answer:

  • Both are composite data types that group related data
  • Records contain only data fields
  • Classes contain data fields AND methods (procedures/functions)
  • Classes define a blueprint for creating objects with behavior
  • Records are simpler structures just for organizing data

Example: A Student record has Name, Age, Grade. A Student CLASS would also have methods like CalculateGPA() or Promote().

9. Glossary

User-Defined Data Type

A data type based on an existing data type or other data types that have been defined by a programmer to match specific program requirements.

Non-Composite Data Type

A data type that can be defined without referencing another data type. It contains only one data item. Examples: enumerated types, pointer types.

Composite Data Type

A data type that references other data types in its definition. It contains multiple data items, often of different types. Examples: records, sets, classes.

Enumerated Data Type

A non-composite data type defined by a given list of all possible values that has an implied order. Values are not strings and are ordinal.

Pointer Data Type

A non-composite data type that uses the memory address of where data is stored. It is a form of indirect referencing.

Dereferencing

The process of accessing the value stored at the memory location that a pointer is pointing to. Done using the ^ symbol in pseudocode.

Record Data Type

A composite data type that contains a fixed number of components (fields), which can be of different data types. Fields are accessed using dot notation.

Set Data Type

A composite data type that represents an unordered collection of unique elements. Supports mathematical operations like union, intersection, and difference.

Class

A composite data type that includes variables of given data types (attributes) and methods (code routines). It is a blueprint for creating objects.

Object

An instance of a class. Multiple objects can be created from the same class, each having its own copy of the class attributes.

Dot Notation

The method of accessing individual fields of a record using the format RecordName.FieldName (e.g., Student.Name).

Ordinal

Having an implied order. Enumerated values are ordinal, meaning they can be used with arithmetic operations like +1 and -1.

10. Exam Success Tips

💡 Non-Composite vs Composite - The Key Difference
💡 Enumerated Types - Remember!
💡 Pointer Symbols - Don't Mix Them Up!
🧠 Memory Tricks

10. Exam Success Tips (Continued)

❌ Common Mistakes to Avoid
💡 When to Use Each Type
Situation Best Type Why
Fixed list of related values Enumerated Restricts to valid options
Working with memory addresses Pointer Indirect referencing
Grouping related data Record Different types together
Unique elements only Set No duplicates allowed
Data with behaviors Class Methods included
💡 Answer Structure Tips

11. Key Takeaways

📌 Summary Points

User-Defined Data Types Overview

Non-Composite Data Types

Composite Data Types

Chapter 13.1 Summary User-Defined Data Types Non-Composite • Enumerated • Pointer Single data type Composite • Record • Set • Class/Object Multiple data types
🌟 Final Reminder

User-defined data types are essential tools for creating well-structured, maintainable programs. They allow you to model real-world entities accurately and make your code easier to understand. Always choose the appropriate type based on your data requirements!