UD

User-Defined Data Types

Creating custom data types to match program requirements

Learning Objectives

By the end of this lesson, you will be able to:

  • Define and differentiate between composite and non-composite data types
  • Create and use enumerated data types in pseudocode
  • Understand and implement pointer data types
  • Work with set data types and their operations
  • Choose appropriate data types for different programming scenarios
  • Explain the benefits of user-defined data types

Key Terms

  • User-defined data type - a data type based on an existing data type or other data types that have been defined by a programmer.
  • Non-composite data type - a data type that does not reference any other data types.
  • Enumerated data type - a non-composite data type defined by a given list of all possible values that has an implied order.
  • Pointer data type - a non-composite data type that uses the memory address of where the data is stored.
  • Set - a given list of unordered elements that can use set theory operations such as intersection and union.
  • Composite data type - a data type that refers to any other data type in its type definition.

What Are User-Defined Data Types?

Programmers use specific data types that exactly match a program's requirements. They define their own data types based on primitive data types provided by a programming language, or data types that they have defined previously in a program. These are called user-defined data types.

User-defined data types can be divided into non-composite and composite data types, providing more precise ways to represent and manipulate data in programs.

Why User-Defined Data Types Matter

Using appropriate data types allows for:

  • More readable and maintainable code
  • Better data validation and type safety
  • More accurate representation of real-world concepts
  • Easier debugging and error detection

Non-Composite Data Types

A non-composite data type can be defined without referencing another data type. It can be a primitive type available in a programming language or a user-defined data type. Non-composite user-defined data types are usually used for a special purpose.

Enumerated Data Types

An enumerated data type contains no references to other data types when it is defined. It consists of a predefined list of values with an implied order.

TYPE TMonth = (January, February, March, ...)
DECLARE thisMonth : TMonth
DECLARE nextMonth : TMonth
thisMonthJanuary
nextMonththisMonth + 1 // February

Pointer Data Types

A pointer data type is used to reference a memory location. This data type needs to have information about the type of data that will be stored in the memory location.

TYPE TMonthPointer = ^TMonth
DECLARE monthPointer : TMonthPointer
monthPointer ← ^thisMonth
DECLARE myMonth : TMonth
myMonthmonthPointer^ // Dereferencing the pointer

Activity 13A: Enumerated Data Types

Difficulty: Easy • Estimated time: 5 minutes

Using pseudocode, declare an enumerated data type for the days of the week. Then declare two variables today and yesterday, assign a value of Wednesday to today, and write a suitable assignment statement for tomorrow.

TYPE TDay = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)

DECLARE today : TDay
DECLARE yesterday : TDay
DECLARE tomorrow : TDay

todayWednesday
yesterdaytoday - 1 // Tuesday
tomorrowtoday + 1 // Thursday

Activity 13B: Pointer Data Types

Difficulty: Medium • Estimated time: 8 minutes

Using pseudocode for the enumerated data type for days of the week, declare a suitable pointer to use. Set your pointer to point at today. Remember, you will need to set up the pointer data type and the pointer variable.

TYPE TDay = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)
TYPE TDayPointer = ^TDay

DECLARE today : TDay
DECLARE dayPointer : TDayPointer

todayWednesday
dayPointer ← ^today

Check Your Understanding: Non-Composite Data Types

  • Enumerated types have an implied order
  • Set types are unordered collections
  • Enumerated types use sequential values
  • Set types support set operations (union, intersection)
  • Use the ^ symbol after the pointer variable
  • Example: myVariable ← pointer^
  • This accesses the value at the memory address
  • Not the address itself
  • Improves code readability
  • Provides type safety
  • Restricts to valid values only
  • Makes code self-documenting
  • Easier to maintain and debug
TYPE TTrafficLight = (Red, Amber, Green)
  • Indicates a pointer data type
  • Shows it references another data type
  • Example: TYPE TPointer = ^TInteger
  • TPointer can point to TInteger variables

Composite Data Types

A data type that refers to any other data type in its type definition is a composite data type. This includes records, sets, and classes.

Record Data Type

A record is a composite data type that groups together related data items of potentially different types.

TYPE TBookRecord
  DECLARE title : STRING
  DECLARE author : STRING
  DECLARE publisher : STRING
  DECLARE noPages : INTEGER
  DECLARE fiction : BOOLEAN
ENDTYPE

Set Data Type

A set is a given list of unordered elements that can use set theory operations such as intersection and union.

TYPE SLetter = SET OF CHAR
DEFINE vowel ('a', 'e', 'i', 'o', 'u') : SLetter

Class Data Type

A class is a composite data type that includes variables of given data types and methods (code routines that can be run by an object in that class).

CLASS Student
  DECLARE name : STRING
  DECLARE age : INTEGER
  DECLARE grade : CHAR

  PROCEDURE displayInfo()
  ENDPROCEDURE
ENDCLASS

Activity 13C: Data Type Selection

Difficulty: Medium • Estimated time: 10 minutes

Choose an appropriate data type for the following situations. Give the reason for your choice in each case.

  1. A fixed number of colors to choose from.
  2. Data about each house that an estate agent has for sale.
  3. The addresses of integer data held in main memory.
  1. Enumerated data type - A fixed set of colors (e.g., Red, Blue, Green) with an implied order makes an enumerated type appropriate.
  2. Record data type - A house record would contain multiple related attributes (address, price, bedrooms, etc.) of different types.
  3. Pointer data type - Pointers are specifically designed to store memory addresses of data.

Check Your Understanding: Composite Data Types

  • References other data types in its definition
  • Combines multiple data elements
  • Examples: records, sets, classes
  • Built from simpler data types
  • Records contain different data types
  • Arrays contain same data type
  • Records use field names to access elements
  • Arrays use indices to access elements
  • Records represent entities with attributes
  • Union - combines elements from both sets
  • Intersection - finds common elements
  • Difference - elements in one set but not the other
  • Membership testing - check if element is in set
TYPE TStudent
  DECLARE name : STRING
  DECLARE studentID : INTEGER
  DECLARE grade : CHAR
  DECLARE age : INTEGER
ENDTYPE
  • Classes include methods (procedures/functions)
  • Records only contain data fields
  • Classes support inheritance
  • Classes enable object-oriented programming
  • Records are simpler data structures

Key Takeaways

  • User-defined data types allow programmers to create custom data structures
  • Non-composite data types don't reference other types (enumerated, pointer)
  • Composite data types reference other types (records, sets, classes)
  • Enumerated types define ordered lists of possible values
  • Pointer types store memory addresses of data
  • Record types group related data of different types
  • Set types represent unordered collections with set operations
  • Class types combine data with methods for object-oriented programming
  • Choosing the right data type improves code clarity and maintainability

Question Bank

Marking Scheme
  • [2 marks] Definition: A data type based on an existing data type or other data types that have been defined by a programmer.
  • [3 marks] Reasons for use:
    • To match program requirements more precisely
    • To improve code readability and maintainability
    • To provide better data validation and type safety
Additional Notes for Slow Learners
  • Think of user-defined data types as creating custom labels for data that make your code easier to understand
  • For example, instead of using integers 1-7 for days, you can create an enumerated type with Monday to Sunday
  • This makes your code self-documenting - anyone reading it can understand what the values represent
Marking Scheme
  • [2 marks] Similarities:
    • Both define collections of values
    • Both restrict variables to specific predefined values
  • [4 marks] Differences:
    • Enumerated types have an implied order, sets are unordered
    • Enumerated types use sequential values, sets don't have sequence
    • Set types support set operations (union, intersection, difference)
    • Enumerated types are typically used for fixed options with order, sets for membership testing
Additional Notes for Slow Learners
  • Think of enumerated types like days of the week - they always come in the same order
  • Think of sets like a bag of colored marbles - no particular order, but you can check if a specific color is in the bag
  • Enumerated: Monday, Tuesday, Wednesday... (order matters)
  • Set: {red, blue, green} or {1, 3, 5} (no order, just membership)
Marking Scheme
  • [2 marks] Correct pointer declaration
  • [2 marks] Correct dereferencing example
TYPE TIntPointer = ^INTEGER
DECLARE num : INTEGER
DECLARE pNum : TIntPointer

num ← 42
pNum ← ^num
OUTPUT pNum^ // Outputs: 42
Additional Notes for Slow Learners
  • A pointer is like a business card - it doesn't contain the actual information, just where to find it
  • Dereferencing is like using the address on the business card to visit the actual office
  • The ^ symbol is used both when declaring pointer types and when dereferencing pointers
  • pNum stores the memory address, pNum^ gets the actual value at that address
Marking Scheme
  • [1 mark] Correct TYPE declaration
  • [4 marks] Appropriate fields (1 mark each for 4 relevant fields)
TYPE TProduct
  DECLARE name : STRING
  DECLARE productID : INTEGER
  DECLARE price : REAL
  DECLARE inStock : BOOLEAN
  DECLARE category : STRING
ENDTYPE
Additional Notes for Slow Learners
  • A record is like a form with multiple fields - each field stores different information about the same thing
  • Think of a product record as an index card for each item in a store
  • Each field has a specific data type that matches the kind of information it stores
  • Records help keep related information together in one place
Marking Scheme
  • [2 marks] Clear explanation of dereferencing
  • [2 marks] Appropriate example with correct pseudocode

Dereferencing accesses the value at a memory address rather than the address itself. It uses the ^ symbol after the pointer variable.

DECLARE value : INTEGER
DECLARE pointer : TIntPointer

value ← 25
pointer ← ^value
OUTPUT pointer^ // Outputs 25 (the value), not the address
Additional Notes for Slow Learners
  • Think of a pointer as a GPS coordinate and dereferencing as actually visiting that location
  • The pointer stores WHERE the data is, dereferencing gets WHAT is at that location
  • Without dereferencing, you just have an address (like having a phone number but not calling it)
  • With dereferencing, you access the actual data (like actually making the phone call)
Marking Scheme
  • [1 mark each] For each valid advantage (up to 5 marks):
    • Improves code readability with meaningful names
    • Restricts variables to valid values only
    • Provides type safety during compilation
    • Makes code self-documenting
    • Easier to maintain and modify
    • Reduces errors from invalid values
Additional Notes for Slow Learners
  • Enumerated types make your code speak English instead of "computer language"
  • Instead of remembering that 1=Monday, 2=Tuesday, you can just use the names directly
  • The compiler will catch mistakes - if you try to assign "Banana" to a day of week variable, it will show an error
  • When you come back to your code months later, you'll still understand what it does
Marking Scheme
  • [2 marks] Correct set type declaration
  • [2 marks] Correct set definition with appropriate values
TYPE SPrime = SET OF INTEGER
DEFINE primes (2, 3, 5, 7) : SPrime
Additional Notes for Slow Learners
  • Sets are like mathematical sets - they contain elements but with no particular order
  • Prime numbers less than 10 are 2, 3, 5, and 7 (1 is not a prime number)
  • The order you list them in doesn't matter - {2,3,5,7} is the same as {7,5,3,2}
  • You can later check if a number is in the set using membership testing
Marking Scheme
  • [1 mark each] For each valid situation (up to 4 marks):
    • When data items are logically related
    • When passing multiple related values to procedures
    • When storing structured data in files or arrays
    • When representing real-world entities with multiple attributes
    • When you need to organize complex data
    • When multiple pieces of data belong together conceptually
Additional Notes for Slow Learners
  • Use records when you have information that naturally belongs together
  • Example: Student record (name, ID, grade) - these all describe one student
  • Without records, you'd have separate variables like studentName, studentID, studentGrade which are harder to manage
  • Records keep related information bundled together, making your code cleaner and more organized
Marking Scheme
  • [2 marks] Correct enumerated type declaration
  • [1 mark] Variable declaration of the enumerated type
  • [1 mark] Assignment of a value
  • [1 mark] Example usage (e.g., in a condition)
TYPE TSuit = (Hearts, Diamonds, Clubs, Spades)
DECLARE cardSuit : TSuit
cardSuitHearts
IF cardSuit = Hearts THEN
  OUTPUT "Red suit"
ENDIF
Additional Notes for Slow Learners
  • Card suits are a perfect example for enumerated types - there are exactly 4 possibilities
  • Instead of using numbers or strings, we use the actual suit names directly in code
  • This prevents errors - you can't accidentally assign "Banana" to a card suit variable
  • The code becomes much more readable - anyone can understand what "Hearts" means
Marking Scheme
  • [2 marks] Definition of class as blueprint/template
  • [2 marks] Definition of object as instance of class
  • [1 mark] Explanation that multiple objects can be created from one class

A class defines the properties and methods that objects will have, while an object is a specific instance of a class with actual data values.

Additional Notes for Slow Learners
  • Think of a class as a cookie cutter and objects as the actual cookies
  • The cookie cutter (class) defines the shape, but the cookies (objects) are the actual things you can eat
  • You can use one cookie cutter (class) to make many cookies (objects)
  • Each cookie (object) might have different decorations (data values) but the same basic shape (class definition)